Skip to content

Commit a42263c

Browse files
committed
Rest of settings, Banword and Roles fix.
Start of Markov command, maybe.
1 parent d4684cd commit a42263c

File tree

33 files changed

+1819
-496
lines changed

33 files changed

+1819
-496
lines changed

.gitignore

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,12 @@ cython_debug/
164164
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
165165

166166
/.data
167+
!/.data/z_log_queries.xml
168+
!/.data/z_clickhouse.xml
169+
167170
dev.txt
168171
.db_data
169172
.redis_data
170173
/.idea
171174
/.vscode
172175
TODOS.md
173-
174-
*/static/node_modules/*

bot/cogs/admin/commands/admin.py

Lines changed: 123 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,23 @@
44
import importlib.util
55
import os
66
import sys
7+
from dataclasses import dataclass
8+
from datetime import datetime
79
from pathlib import Path
810
from typing import TYPE_CHECKING
911

1012
from bot.ext import Context, Response, commands
13+
from bot.models import Channel as ChannelBot
1114
from bot.utils import Role, SessionsCaches, StringTools
1215
from bot.utils.singleton import Singleton
1316

1417
from .translations import Translations
1518

19+
# from bot.models import User as UserBot
20+
# import asyncio
21+
# import asyncmy
22+
# from asyncmy.cursors import DictCursor
23+
1624
if TYPE_CHECKING:
1725
from bot.bot import Gorenmu
1826

@@ -35,8 +43,8 @@ async def component_command_error(self, payload: commands.CommandErrorPayload) -
3543
def is_dev(self, ctx: Context) -> bool:
3644
return Role.dev(ctx)
3745

38-
@commands.command(name="nada", aliases=["bonjour", "hello"])
39-
async def nada(self, ctx: Context, *, args: str) -> Response:
46+
@commands.command(name="nada", aliases=[])
47+
async def nada(self, ctx: Context, *, args: str = "") -> Response:
4048
# if " " in args:
4149
# command, subcommand = args.split()
4250
# command = ctx.bot.get_command(command)
@@ -48,8 +56,39 @@ async def nada(self, ctx: Context, *, args: str) -> Response:
4856
# teste = command.component.translations.get_decorator(ctx=command)
4957
# teste2 = teste.deco_usage(ctx, prefix=ctx.prefix)
5058
# await ctx.reply(teste2)
51-
return self.translations.Nada.nada(ctx, args + self.StringTools.inv_char())
52-
# return self.translations.Exceptions.empty(ctx, args)
59+
# channel = self.bot.channels[ctx.channel.name.lower()]
60+
channel = await ChannelBot.get(user_id=192923262)
61+
markov = await self.bot.MarkovProcessor.generate(args, channel=channel, max_length=25)
62+
await self.bot.ContextHandler.simple_response(ctx, str(self.bot.MarkovProcessor.queue.async_q.qsize()))
63+
64+
# return self.translations.Nada.nada(ctx, args + self.StringTools.inv_char())
65+
return self.translations.Exceptions.echo(ctx, markov)
66+
67+
# @commands.command(name="nada2", aliases=[])
68+
# async def nada2(self, ctx: Context, *, args: str) -> Response:
69+
# channel = self.bot.channels[ctx.channel.name.lower()]
70+
# user = ctx.user
71+
# rows = await fetch_message_logs(ctx)
72+
# # with open("texts.txt") as text:
73+
# # mensagens = text.readlines()
74+
# # for msg in mensagens:
75+
# # await self.bot.MarkovProcessor.queue.async_q.put((msg, channel, user))
76+
# for row in rows:
77+
# try:
78+
# user, success = await UserBot.get_or_create(id=row["user"].id, name=row["user"].name)
79+
# if row['channel'].id not in [411010313, 926706091, 707980467, 54966942, 744028864, ]:
80+
# channel, success = await ChannelBot.get_or_create(user_id=row['channel'].id)
81+
# if channel not in self.bot.channels and not channel.removed:
82+
# channel.removed = True
83+
# await channel.save()
84+
# else:
85+
# channel = await ChannelBot.get(user_id=row['channel'].id)
86+
#
87+
# await self.bot.MarkovProcessor.queue.async_q.put((row['message_row'].content, channel, user))
88+
# except Exception as e:
89+
# print(e)
90+
# markov = await self.bot.MarkovProcessor.generate(args, channel=channel)
91+
# return self.translations.Exceptions.echo(ctx, markov)
5392

5493
@commands.command(name="restart", aliases=[])
5594
async def restart(self, ctx: Context) -> Response:
@@ -94,6 +133,18 @@ async def reload(self, ctx: Context, command: str, *, extras=False) -> Response:
94133
"class": "CommandHandler",
95134
"args": [self.bot],
96135
},
136+
"context_handler": {
137+
"attr": "ContextHandler",
138+
"module": "bot.handlers.context_handler",
139+
"class": "ContextHandler",
140+
"args": [self.bot],
141+
},
142+
"markov_handler": {
143+
"attr": "MarkovProcessor",
144+
"module": "bot.utils.markov_tools",
145+
"class": "MarkovProcessor",
146+
"args": [self.bot],
147+
},
97148
}
98149

99150
if command == "commands":
@@ -161,6 +212,27 @@ async def setup(bot: Gorenmu) -> None:
161212
async def teardown(bot: Gorenmu) -> None: ... # NOQA
162213

163214

215+
@dataclass
216+
class User:
217+
id: int
218+
name: str
219+
220+
221+
@dataclass
222+
class Channel:
223+
id: int
224+
225+
226+
@dataclass
227+
class MessageLog:
228+
id: int
229+
content: str
230+
type: str
231+
created_at: datetime
232+
channel_id: int | None
233+
user_id: int
234+
235+
164236
async def reload_component(bot_obj, attr_name: str, module_name: str, class_name: str, args: list | None = None):
165237
from bot.utils.reload_util import reload_and_get_authorized
166238

@@ -183,3 +255,50 @@ async def reload_component(bot_obj, attr_name: str, module_name: str, class_name
183255
except Exception as e:
184256
bot_obj.log.error(f"Error reloading {attr_name}: {e}")
185257
raise
258+
259+
260+
#
261+
# async def fetch_message_logs(ctx: Context):
262+
# connection_config = {
263+
# "host": "127.0.0.1",
264+
# "port": 12398,
265+
# "user": ctx.bot.config.DatabaseConfig.login,
266+
# "password": ctx.bot.config.DatabaseConfig.password,
267+
# "database": ctx.bot.config.DatabaseConfig.database_uri,
268+
# }
269+
# conn = await asyncmy.connect(**connection_config) # NOQA
270+
# try:
271+
# async with conn.cursor(DictCursor) as cursor:
272+
# query = """
273+
# SELECT
274+
# m.id AS m_id, m.content, m.type, m.created_at, m.channel_id, m.user_id,
275+
# u.id AS u_id, u.name AS u_name,
276+
# c.id AS c_id
277+
# FROM mensage_logs m
278+
# INNER JOIN user u ON m.user_id = u.id
279+
# LEFT JOIN channel c ON m.channel_id = c.id
280+
# ORDER BY m.id DESC
281+
# LIMIT 100000;
282+
# """
283+
#
284+
# await cursor.execute(query)
285+
# results = await cursor.fetchall()
286+
#
287+
# rows = []
288+
# for r in results:
289+
# user_obj = User(id=r["u_id"], name=r["u_name"])
290+
# channel_obj = Channel(id=r["c_id"]) if r["c_id"] else None
291+
# msg_obj = MessageLog(
292+
# id=r["m_id"],
293+
# content=r["content"],
294+
# type=r["type"],
295+
# created_at=r["created_at"],
296+
# channel_id=r["channel_id"],
297+
# user_id=r["user_id"],
298+
# )
299+
# rows.append({"message_row": msg_obj, "user": user_obj, "channel": channel_obj})
300+
# return rows
301+
#
302+
# finally:
303+
# await conn.ensure_closed()
304+
#

bot/cogs/join/command/join.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ async def component_before_invoke(self, ctx: Context) -> None:
3333

3434
# TODO: add more scopes later, fix get_or_none to user_id
3535
# TODO: also add explanations for scopes
36-
@commands.command(name='join', aliases=[])
36+
@commands.command(name='join', aliases=[], whispable=True)
3737
async def join(self, ctx: Context, args: str = "") -> Response:
3838
channel = await Channel.get_or_none(user_id=ctx.user.id)
3939
args, lang = self.StringTools.remove_prefixed_option(args, "lang")

bot/cogs/leave/command/leave.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,23 +29,24 @@ def guards_component(self, ctx: commands.Context) -> bool: # NOQA
2929
async def component_before_invoke(self, ctx: Context) -> None:
3030
self.translations.ctx_set(ctx)
3131

32-
@commands.command(name="leave", aliases=[])
32+
@commands.command(name="leave", aliases=[], whispable=True)
3333
async def leave(self, ctx: Context) -> Response:
3434
if not (channel := await Channel.get_or_none(user=ctx.user)):
3535
return self.translations.Leave.not_on_channel()
3636
if channel.removed:
3737
return self.translations.Leave.not_on_channel()
3838
await self.bot.TokensHandler.get_event_sub_subscriptions()
39-
user_token = await TwitchTokens.get(user=ctx.user)
40-
user_token.token = None
41-
user_token.refresh = None
42-
user_token.removed = True
43-
await user_token.save()
39+
user_token = await TwitchTokens.get_or_none(user=ctx.user)
40+
if user_token:
41+
user_token.token = None
42+
user_token.refresh = None
43+
user_token.removed = True
44+
await user_token.save()
4445
channel.removed = True
4546
channel.online = False
4647
await channel.save()
4748
for sub in channel.event_subs:
48-
await self.bot.delete_eventsub_subscription(sub)
49+
await self.bot.delete_eventsub_subscription(channel.event_subs[sub])
4950
await self.bot.ChannelHandler.load_channels()
5051
return self.translations.Leave.channel_removed(ctx.author.name)
5152

bot/cogs/set/command/set.py

Lines changed: 117 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from typing import TYPE_CHECKING
66

77
from bot.ext import Context, Response, commands
8-
from bot.utils import StringTools
8+
from bot.utils import Role, StringTools
99

1010
from .translations import Translations
1111

@@ -29,11 +29,14 @@ async def component_command_error(self, payload: commands.CommandErrorPayload) -
2929
def guards_component(self, ctx: commands.Context) -> bool: # NOQA
3030
return True
3131

32+
async def component_before_invoke(self, ctx: Context) -> None:
33+
self.translations.ctx_set(ctx)
34+
3235
@commands.group(name="set", aliases=[], invoke_fallback=True)
3336
async def set(self, ctx: Context, *, args) -> Response:
3437
return self.translations.Exceptions.echo(ctx, args)
3538

36-
@set.command(name="mention", aliases=[])
39+
@set.command(name="mention", aliases=[], pipeble=False)
3740
async def set_mention(self, ctx: Context, *, args: str) -> Response:
3841
translations = self.translations.Mention
3942
if args.lower() not in ["on", "off"]:
@@ -58,7 +61,7 @@ async def set_city(self, ctx: Context, *, args: str) -> Response:
5861
await ctx.user.save()
5962
return translations.city_added(ctx)
6063

61-
@set.command(name="nick", aliases=["nickname"])
64+
@set.command(name="nick", aliases=["nickname"], pipeble=False)
6265
async def set_nick(self, ctx: Context, *, args: str) -> Response:
6366
translations = self.translations.Nick
6467
nickname = args
@@ -74,7 +77,7 @@ async def set_nick(self, ctx: Context, *, args: str) -> Response:
7477
await ctx.user.save()
7578
return translations.nick_changed(ctx)
7679

77-
@set.command(name="color", aliases=[])
80+
@set.command(name="color", aliases=[], pipeble=False)
7881
async def set_color(self, ctx: Context, *, args: str) -> Response:
7982
translations = self.translations.Color
8083
if args.lower() == "remove":
@@ -87,7 +90,7 @@ async def set_color(self, ctx: Context, *, args: str) -> Response:
8790
await ctx.user.save()
8891
return translations.color_changed(ctx, color)
8992

90-
@set.command(name="reminder", aliases=[])
93+
@set.command(name="reminder", aliases=[], pipeble=False)
9194
async def set_reminder(self, ctx: Context, *, args: str) -> Response:
9295
translations = self.translations.Reminder
9396
if args.lower() not in ["on", "off"]:
@@ -101,6 +104,115 @@ async def set_reminder(self, ctx: Context, *, args: str) -> Response:
101104
await ctx.user.save()
102105
return translations.reminder_off(ctx)
103106

107+
@commands.guard([Role.admin])
108+
@set.command(name="banword", aliases=[])
109+
async def set_banword(self, ctx: Context, action: str, *, args: str) -> Response:
110+
translations = self.translations.Banword
111+
words = translations.add_remove_lang()
112+
_words = self.StringTools.extract_words_simple(args)
113+
add, remove, clean = words.get("add"), words.get("remove"), words.get("clean")
114+
channel = self.bot.channels[ctx.channel.name.lower()]
115+
if channel.removed:
116+
return translations.who()
117+
if action.lower() not in ["add", "remove", "clean", *clean, *add, *remove]:
118+
await self._send_bug(ctx, ctx.channel.name)
119+
return translations.add_remove(action)
120+
if action.lower() in ["add", *add]:
121+
for world in _words:
122+
channel.banwords[world] = int(ctx.author.id)
123+
await channel.save()
124+
return translations.added()
125+
elif action.lower() in ["remove", *remove]:
126+
for world in _words:
127+
channel.banwords.pop(world)
128+
await channel.save()
129+
return translations.removed()
130+
elif action.lower() in ["clean", *clean]:
131+
channel.banwords = {}
132+
return translations.cleaned()
133+
else:
134+
return translations.what(action)
135+
136+
@commands.guard([Role.admin])
137+
@set.command(name="enable", aliases=["disable"], pipeble=False)
138+
async def set_enable_disable(self, ctx: Context, arg: str) -> Response:
139+
translations = self.translations.Enable
140+
channel = self.bot.channels[ctx.channel.name.lower()]
141+
invoked = ctx.invoked_with.lower()
142+
protected_commands = {"set", "enable", "disable", "help", "start", "stop"}
143+
if arg.lower() in protected_commands:
144+
return translations.why(arg)
145+
if arg.lower() == "all":
146+
if invoked == "set enable":
147+
channel.disabled.clear()
148+
await channel.save()
149+
return translations.all_enabled()
150+
elif invoked == "set disable":
151+
for cmd in ctx.bot.commands:
152+
if ctx.bot.commands[cmd].name not in protected_commands:
153+
channel.disabled[ctx.bot.commands[cmd].name.lower()] = int(ctx.author.id)
154+
await channel.save()
155+
return translations.all_disabled()
156+
command_to_manage = ctx.bot.get_command(arg.lower())
157+
if not command_to_manage:
158+
return translations.no_command(arg)
159+
if invoked == "set enable":
160+
if command_to_manage.name not in channel.disabled:
161+
return translations.command_already_enabled(arg)
162+
channel.disabled.pop(command_to_manage.name.lower(), None)
163+
await channel.save()
164+
return translations.command_enabled(arg)
165+
elif invoked == "set disable":
166+
if command_to_manage.name in protected_commands:
167+
return translations.why(arg)
168+
if command_to_manage.name in channel.disabled:
169+
return translations.command_already_disabled(arg)
170+
channel.disabled[command_to_manage.name.lower()] = int(ctx.author.id)
171+
await channel.save()
172+
return translations.command_disabled(arg)
173+
return translations.options()
174+
175+
@commands.guard([Role.admin])
176+
@set.command(name="prefix", aliases=[], pipeble=False)
177+
async def set_prefix(self, ctx: Context, arg: str) -> Response:
178+
translations = self.translations.Prefix
179+
prefix_size = 2
180+
if len(arg) >= prefix_size:
181+
return translations.too_long(arg, prefix_size)
182+
channel = self.bot.channels[ctx.channel.name.lower()]
183+
channel.prefix = arg
184+
await channel.save()
185+
return translations.prefix_changed(arg)
186+
187+
@commands.guard([Role.admin])
188+
@set.command(name="start", aliases=["on", "stop", "off"], pipeble=False, whispable=True)
189+
async def set_start_stop(self, ctx: Context) -> Response:
190+
translations = self.translations.StartStop
191+
invoked = ctx.invoked_with.lower()
192+
channel = self.bot.channels[ctx.channel.name.lower()]
193+
if invoked.lower() in ["set start", "set on"]:
194+
if channel.online:
195+
return translations.already_on()
196+
channel.online = True
197+
await channel.save()
198+
return translations.started()
199+
elif invoked.lower() in ["set stop", "set off"]:
200+
await channel.save()
201+
if channel.online:
202+
channel.online = False
203+
await channel.save()
204+
return translations.stopped()
205+
return translations.already_off()
206+
return translations.shrug()
207+
208+
async def _send_bug(self, ctx: Context, name: str):
209+
if self.bot.mock:
210+
return None
211+
fake_exc = self.translations.SupportTools.fake_stacktrace(
212+
f"Somehow a command has invoked for removed channel: {name}"
213+
)
214+
return await self.bot.CommandHandler.send_bug(ctx, fake_exc)
215+
104216

105217
async def setup(bot: Gorenmu) -> None:
106218
await bot.add_component(SetCmd(bot))

0 commit comments

Comments
 (0)