Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

m.thread: Update modules #211

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions modules/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async def matrix_message(self, bot, room, event):
bot.module_aliases.update({args[0]: args[1]})
self.aliases.update({args[0]: args[1]})
bot.save_settings()
await bot.send_text(room, f'Aliased !{args[0]} to !{args[1]}')
await bot.send_text(room, f'Aliased !{args[0]} to !{args[1]}', event)

elif len(args) == 2:
if args.pop(0) in ['rm', 'remove']:
Expand All @@ -43,7 +43,7 @@ async def matrix_message(self, bot, room, event):
old = bot.module_aliases.pop(args[0])
self.aliases.pop(args[0])
bot.save_settings()
await bot.send_text(room, f'Removed alias !{args[0]}')
await bot.send_text(room, f'Removed alias !{args[0]}', event)

elif len(args) == 1:
if args.pop(0) in ['ls', 'list']:
Expand All @@ -55,10 +55,10 @@ async def matrix_message(self, bot, room, event):
for k, v in inverted.items():
v = ', '.join(v)
msg.append(f'- {k} = {v}')
await bot.send_text(room, '\n'.join(msg))
await bot.send_text(room, '\n'.join(msg), event)

elif args.pop(0) == 'help':
await bot.send_text(room, self.long_help(bot=bot, event=event))
await bot.send_text(room, self.long_help(bot=bot, event=event), event)

def help(self):
return 'Manage command aliases'
Expand Down
44 changes: 22 additions & 22 deletions modules/apod.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,51 +53,51 @@ async def matrix_message(self, bot, room, event):
await self.send_apod(bot, room, self.apod_api_url)
elif len(args) == 2:
if args[1] == "stats":
await self.send_stats(bot, room)
await self.send_stats(bot, room, event)
elif args[1] == "clear":
bot.must_be_owner(event)
await self.clear_uri_cache(bot, room)
await self.clear_uri_cache(bot, room, event)
elif args[1] == "help":
await self.command_help(bot, room)
await self.command_help(bot, room, event)
elif args[1] == "avatar":
await self.send_apod(bot, room, self.apod_api_url, set_room_avatar=bot.is_admin(room, event))
await self.send_apod(bot, room, event, self.apod_api_url, set_room_avatar=bot.is_admin(room, event))
else:
date = args[1]
if re.match(self.APOD_DATE_PATTERN, date) is not None:
uri = self.apod_by_date_api_url + date
await self.send_apod(bot, room, uri)
await self.send_apod(bot, room, event, uri)
else:
await bot.send_text(room, "invalid date. accepted: YYYY-MM-DD")
await bot.send_text(room, "invalid date. accepted: YYYY-MM-DD", event)
elif len(args) == 3:
if args[1] == "apikey":
await self.update_api_key(bot, room, event, args[2])
elif args[1] == "avatar":
date = args[2]
if re.match(self.APOD_DATE_PATTERN, date) is not None:
uri = self.apod_by_date_api_url + date
await self.send_apod(bot, room, uri, set_room_avatar=bot.is_admin(room, event))
await self.send_apod(bot, room, event, uri, set_room_avatar=bot.is_admin(room, event))
else:
await bot.send_text(room, "invalid date. accepted: YYYY-MM-DD")
await bot.send_text(room, "invalid date. accepted: YYYY-MM-DD", event)

async def send_apod(self, bot, room, uri, set_room_avatar=False):
async def send_apod(self, bot, room, event, uri, set_room_avatar=False):
self.logger.debug(f"send request using uri {uri}")
response = requests.get(uri)

if response.status_code == 400:
self.logger.error("unable to request apod api. status: %d text: %s", response.status_code, response.text)
return await bot.send_text(room, response.json().get("msg"))
return await bot.send_text(room, response.json().get("msg"), event)

if response.status_code != 200:
self.logger.error("unable to request apod api. response: [status: %d text: %s]", response.status_code, response.text)
return await bot.send_text(room, "sorry. something went wrong accessing the api :(")
return await bot.send_text(room, "sorry. something went wrong accessing the api :(", event)

apod = Apod.create_from_json(response.json())
self.logger.debug(apod)

if apod.media_type != "image":
return await self.send_unknown_mediatype(room, bot, apod)

await bot.send_html(room, f"<b>{html.escape(apod.title)} ({html.escape(apod.date)})</b>", f"{apod.title} ({apod.date})")
await bot.send_html(room, f"<b>{html.escape(apod.title)} ({html.escape(apod.date)})</b>", f"{apod.title} ({apod.date})", event)
try:
matrix_uri = None
matrix_uri, mimetype, w, h, size = bot.get_uri_cache(apod.hdurl)
Expand All @@ -106,9 +106,9 @@ async def send_apod(self, bot, room, uri, set_room_avatar=False):
try:
matrix_uri, mimetype, w, h, size = await bot.upload_image(apod.hdurl)
except (UploadFailed, TypeError, ValueError):
await bot.send_text(room, f"Something went wrong uploading {apod.hdurl}.")
await bot.send_image(room, matrix_uri, apod.hdurl, mimetype, w, h, size)
await bot.send_text(room, f"{apod.explanation}")
await bot.send_text(room, f"Something went wrong uploading {apod.hdurl}.", event)
await bot.send_image(room, matrix_uri, apod.hdurl, event, mimetype, w, h, size)
await bot.send_text(room, f"{apod.explanation}", event)
if matrix_uri and set_room_avatar:
await bot.set_room_avatar(room, matrix_uri, mimetype, w, h, size)

Expand Down Expand Up @@ -138,16 +138,16 @@ def set_settings(self, data):
def help(self):
return 'Sends latest Astronomy Picture of the Day to the room. (https://apod.nasa.gov/apod/astropix.html)'

async def send_stats(self, bot, room):
async def send_stats(self, bot, room, event):
msg = f"collected {len(self.matrix_uri_cache)} upload matrix uri's"
await bot.send_text(room, msg)
await bot.send_text(room, msg, event)

async def clear_uri_cache(self, bot, room):
async def clear_uri_cache(self, bot, room, event):
self.matrix_uri_cache.clear()
bot.save_settings()
await bot.send_text(room, "cleared uri cache")
await bot.send_text(room, "cleared uri cache", event)

async def command_help(self, bot, room):
async def command_help(self, bot, room, event):
msg = """commands:
- YYYY-MM-DD - date of the APOD image to retrieve (ex. 2020-03-15)
- stats - show information about uri cache
Expand All @@ -156,12 +156,12 @@ async def command_help(self, bot, room):
- help - show command help
- avatar, avatar YYYY-MM-DD - Additionally set the room's avatar to the fetched image (Must be done as admin)
"""
await bot.send_text(room, msg)
await bot.send_text(room, msg, event)

async def update_api_key(self, bot, room, event, apikey):
bot.must_be_owner(event)
self.api_key = apikey
self.update_api_urls()
bot.save_settings()
await bot.send_text(room, 'Api key set')
await bot.send_text(room, 'Api key set', event)

42 changes: 21 additions & 21 deletions modules/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ async def matrix_message(self, bot, room, event):
pass

# TODO: Make this configurable. By default don't say anything.
# await bot.send_text(room, 'Unknown command, sorry.')
# await bot.send_text(room, 'Unknown command, sorry.', event)

async def get_ping(self, bot, room, event):
self.logger.info(f'{event.sender} pinged the bot in {room.room_id}')

# initial pong
serv_before = event.server_timestamp
local_before = time.time()
pong = await bot.send_text(room, 'Pong!')
pong = await bot.send_text(room, 'Pong!', event)
local_delta = int((time.time() - local_before) * 1000)

# ask the server what the timestamp was on our pong
Expand Down Expand Up @@ -116,7 +116,7 @@ async def get_ping(self, bot, room, event):
async def leave(self, bot, room, event):
bot.must_be_admin(room, event)
self.logger.info(f'{event.sender} asked bot to leave room {room.room_id}')
await bot.send_text(room, f'By your command.')
await bot.send_text(room, f'By your command.', event)
await bot.client.room_leave(room.room_id)

async def stats(self, bot, room):
Expand All @@ -141,7 +141,7 @@ async def stats(self, bot, room):
homeservers = ', '.join(['{} ({} users, {:.1f}%)'.format(hs[0], hs[1], 100.0 * hs[1] / usercount)
for hs in homeservers[:10]])
await bot.send_text(room, f'I\'m seeing {usercount} users in {roomcount} rooms.'
f' Top ten homeservers (out of {hscount}): {homeservers}')
f' Top ten homeservers (out of {hscount}): {homeservers}', event)

async def status(self, bot, room):
systime = time.time()
Expand All @@ -150,11 +150,11 @@ async def status(self, bot, room):
enabled = sum(1 for module in bot.modules.values() if module.enabled)

return await bot.send_text(room, f'Uptime: {uptime} - System time: {systime} '
f'- {enabled} modules enabled out of {len(bot.modules)} loaded.')
f'- {enabled} modules enabled out of {len(bot.modules)} loaded.', event)

async def reload(self, bot, room, event):
bot.must_be_owner(event)
msg = await bot.send_text(room, f'Reloading modules...')
msg = await bot.send_text(room, f'Reloading modules...', event)
bot.stop()
bot.reload_modules()
bot.start()
Expand All @@ -174,11 +174,11 @@ async def reload(self, bot, room, event):
await bot.client.room_send(room.room_id, 'm.room.message', content)

async def version(self, bot, room):
await bot.send_text(room, f'Hemppa version {bot.version} - https://github.com/vranki/hemppa')
await bot.send_text(room, f'Hemppa version {bot.version} - https://github.com/vranki/hemppa', event)

async def quit(self, bot, room, event):
bot.must_be_owner(event)
await bot.send_text(room, f'Quitting, as requested')
await bot.send_text(room, f'Quitting, as requested', event)
self.logger.info(f'{event.sender} commanded bot to quit, so quitting..')
bot.bot_task.cancel()

Expand All @@ -190,8 +190,8 @@ async def enable_module(self, bot, room, event, module_name):
module.enable()
module.matrix_start(bot)
bot.save_settings()
return await bot.send_text(room, f"Module {module_name} enabled")
return await bot.send_text(room, f"Module with name {module_name} not found. Execute !bot modules for a list of available modules")
return await bot.send_text(room, f"Module {module_name} enabled", event)
return await bot.send_text(room, f"Module with name {module_name} not found. Execute !bot modules for a list of available modules", event)

async def disable_module(self, bot, room, event, module_name):
bot.must_be_owner(event)
Expand All @@ -201,20 +201,20 @@ async def disable_module(self, bot, room, event, module_name):
try:
module.disable()
except ModuleCannotBeDisabled:
return await bot.send_text(room, f"Module {module_name} cannot be disabled.")
return await bot.send_text(room, f"Module {module_name} cannot be disabled.", event)
except Exception as e:
return await bot.send_text(room, f"Module {module_name} was not disabled: {repr(e)}")
return await bot.send_text(room, f"Module {module_name} was not disabled: {repr(e)}", event)
module.matrix_stop(bot)
bot.save_settings()
return await bot.send_text(room, f"Module {module_name} disabled")
return await bot.send_text(room, f"Module with name {module_name} not found. Execute !bot modules for a list of available modules")
return await bot.send_text(room, f"Module {module_name} disabled", event)
return await bot.send_text(room, f"Module with name {module_name} not found. Execute !bot modules for a list of available modules", event)

async def show_modules(self, bot, room):
modules_message = "Modules:\n"
for modulename, module in collections.OrderedDict(sorted(bot.modules.items())).items():
state = 'Enabled' if module.enabled else 'Disabled'
modules_message += f"{state}: {modulename} - {module.help()}\n"
await bot.send_text(room, modules_message)
await bot.send_text(room, modules_message, event)

async def export_settings(self, bot, event, module_name=None):
bot.must_be_owner(event)
Expand All @@ -224,7 +224,7 @@ async def export_settings(self, bot, event, module_name=None):
self.logger.info(f"{event.sender} is exporting settings for module {module_name}")
else:
self.logger.info(f"{event.sender} is exporting all settings")
await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', json.dumps(data))
await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', json.dumps(data), event)

async def import_settings(self, bot, event):
bot.must_be_owner(event)
Expand Down Expand Up @@ -254,7 +254,7 @@ async def import_settings(self, bot, event):
child[key] = data
bot.load_settings(account_data)
bot.save_settings()
await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', 'Updated bot settings')
await bot.send_msg(event.sender, f'Private message from {bot.matrix_user}', 'Updated bot settings', event)

async def last_logs(self, bot, room, event, target):
bot.must_be_owner(event)
Expand All @@ -278,13 +278,13 @@ async def last_logs(self, bot, room, event, target):
except (KeyError, TypeError):
pass
else:
return await bot.send_text(msg_room, f'Unknown module {target}, or no logs yet')
return await bot.send_text(msg_room, f'Unknown module {target}, or no logs yet', event)

if count:
logs = logs[count:]
logs = '\n'.join([self.loghandler.format(record) for record in logs])

return await bot.send_html(msg_room, f'<strong>Logs for {key}:</strong>\n<pre><code class="language-txt">{escape(logs)}</code></pre>', f'Logs for {key}:\n' + logs)
return await bot.send_html(msg_room, f'<strong>Logs for {key}:</strong>\n<pre><code class="language-txt">{escape(logs)}</code></pre>', f'Logs for {key}:\n' + logs, event)

async def manage_uri_cache(self, bot, room, event, action):
bot.must_be_owner(event)
Expand All @@ -293,7 +293,7 @@ async def manage_uri_cache(self, bot, room, event, action):
msg = [f'uri cache size: {len(bot.uri_cache)}']
for key, val in bot.uri_cache.items():
msg.append('- ' + key + ': ' + val[0])
return await bot.send_text(room, '\n'.join(msg))
return await bot.send_text(room, '\n'.join(msg), event)
if action in ['clean', 'clear']:
self.logger.info(f"{event.sender} wants to clear the uri cache")
bot.uri_cache = dict()
Expand All @@ -305,7 +305,7 @@ async def rooms(self, bot, room, event):
for croomid in bot.client.rooms:
roomobj = bot.get_room_by_id(croomid)
output = output + f' - {roomobj.display_name} ( {roomobj.machine_name} )\n'
await bot.send_text(room, output)
await bot.send_text(room, output, event)

def disable(self):
raise ModuleCannotBeDisabled
Expand Down
18 changes: 9 additions & 9 deletions modules/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ async def matrix_message(self, bot, room, event):
command_name = args[1]
bot.must_be_owner(event)
if command_name in self.commands:
await bot.send_text(room, f'Removed "{self.commands[command_name]}"')
await bot.send_text(room, f'Removed "{self.commands[command_name]}"', event)
del self.commands[command_name]
bot.save_settings()
else:
await bot.send_text(room, f'Could not find command "{command_name}"')
await bot.send_text(room, f'Could not find command "{command_name}"', event)
# Message body possibilities:
# ["add", "command_name", "echo", "Hello", "world"]
elif args[0] == 'add':
Expand All @@ -38,18 +38,18 @@ async def matrix_message(self, bot, room, event):
bot.must_be_owner(event)
self.commands[command_name] = command_body
bot.save_settings()
await bot.send_text(room, f'Added "{command_name}" -> "{command_body}".')
await bot.send_text(room, f'Added "{command_name}" -> "{command_body}".', event)
# Message body possibilities:
# ["list"]
elif args[0] == 'list':
if len(self.commands) == 0:
await bot.send_text(room, "No known commands")
await bot.send_text(room, "No known commands", event)
else:
known_commands = "Known commands:\n"
for command_name in self.commands.keys():
command_body = self.commands[command_name]
known_commands += f' - "{command_name}" -> "{command_body}"\n'
await bot.send_text(room, known_commands)
await bot.send_text(room, known_commands, event)
# Message body possibilities:
# ["command_name"]
else:
Expand All @@ -60,9 +60,9 @@ async def matrix_message(self, bot, room, event):
f"room: {room.display_name} sender: {event.sender} wants to run cmd {target_command}"
)
out = self.run_command(target_command, event.sender, room.display_name)
await self.send_output(bot, room, out)
await self.send_output(bot, room, out, event)
else:
await bot.send_text(room, 'Unknown command.')
await bot.send_text(room, 'Unknown command.', event)

def help(self):
return 'Runs shell commands'
Expand Down Expand Up @@ -96,10 +96,10 @@ def run_command(self, command, user, roomname):
processout = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5, text=True, env=environment)
return processout.stdout

async def send_output(self, bot, room, output):
async def send_output(self, bot, room, output, event):
html = output
if output.count('\n') > 1:
html = "<pre>" + output + "</pre>"
if len(output) == 0:
output = html = '(No output returned)'
await bot.send_html(room, html, output)
await bot.send_html(room, html, output, event)
Loading