浏览代码

Custom context for message tracking

master
Skyweb 1年前
父节点
当前提交
9f94fd2680
共有 7 个文件被更改,包括 49 次插入59 次删除
  1. +2
    -1
      .gitignore
  2. +12
    -22
      cogs/admin.py
  3. +6
    -11
      cogs/lastfm.py
  4. +7
    -9
      cogs/misc.py
  5. +1
    -1
      cogs/template.py
  6. +16
    -13
      utils/sorachan.py
  7. +5
    -2
      utils/sorahelp.py

+ 2
- 1
.gitignore 查看文件

@@ -1,2 +1,3 @@
utils/config\.py
*.pyc
*.pyc
.vscode*

+ 12
- 22
cogs/admin.py 查看文件

@@ -80,8 +80,7 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):
try:
exec(to_compile, env)
except Exception as e:
context.responses.append(
await context.send(f'```py\n{e.__class__.__name__}: {e}\n```'))
await context.send(f'```py\n{e.__class__.__name__}: {e}\n```')

return

@@ -91,9 +90,7 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):
result = await func()
except Exception:
value = stdout.getvalue()
context.responses.append(
await
context.send(f'```py\n{value}{traceback.format_exc()}\n```'))
await context.send(f'```py\n{value}{traceback.format_exc()}\n```')

try:
await context.message.add_reaction('❌')
@@ -109,24 +106,21 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):

if result is None:
if value:
context.responses.append(
await context.send(f'```py\n{value}\n```'))
await context.send(f'```py\n{value}\n```')
else:
context.responses.append(await
context.send(f'```No output```'))
await context.send(f'```No output```')
else:
context.responses.append(
await context.send(f'```py\n{value}{result}\n```'))
await context.send(f'```py\n{value}{result}\n```')

@commands.command(aliases=['quit'])
async def restart(self, context):
"""Hmm, I wonder"""

context.responses.append(await context.send('Okay, be right back!'))
await context.send('Okay, be right back!')
await self.bot.close()

@commands.command()
async def cogs(self, context):
@commands.command(name="cogs")
async def _cogs(self, context):
cogs = await self.cogs.get_all()
message = f'The following cogs are available:\n' + '\n'.join(
f'{cog["name"]}, {cog["enabled"]}' for cog in cogs)
@@ -143,8 +137,7 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):
try:
load(f'cogs.{name}')
except commands.ExtensionError as e:
context.responses.append(
await context.send(f'Loading "{name}" failed: \n```{e}```'))
await context.send(f'Loading "{name}" failed: \n```{e}```')

return

@@ -154,8 +147,7 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):
elif not cog['enabled']:
await self.cogs.update(name, True)

context.responses.append(await
context.send(f'{name} has been {action}'))
await context.send(f'{name} has been {action}')

@commands.command()
async def unload(self, context, name):
@@ -164,8 +156,7 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):
try:
self.bot.unload_extension(f'cogs.{name}')
except commands.ExtensionError as e:
context.responses.append(
await context.send(f'Disabling "{name}" failed: \n```{e}```'))
await context.send(f'Disabling "{name}" failed: \n```{e}```')

return

@@ -175,8 +166,7 @@ class Admin(commands.Cog, command_attrs=dict(hidden=True)):
elif cog['enabled']:
await self.cogs.update(name, False)

context.responses.append(await
context.send(f'{name} has been disabled'))
await context.send(f'{name} has been disabled')


def setup(bot):

+ 6
- 11
cogs/lastfm.py 查看文件

@@ -52,24 +52,20 @@ class LastFM(commands.Cog):
if user:
await self.send_nowplaying(context, member, user['username'])
else:
context.responses.append(
await
context.send(f'{member.display_name} isn\'t linked...'))
await context.send(f'{member.display_name} isn\'t linked...')

@nowplaying.error
async def nowplaying_handler(self, context, error):
if (isinstance(error, commands.CommandInvokeError)
and isinstance(error.original, UserNotFound)):
context.responses.append(await
context.send("Linked user not found"))
await context.send("Linked user not found")
else:
raise error

async def send_nowplaying(self, context, member, username):
recent_tracks = await self.fetch_recent_tracks(username)
if len(recent_tracks['recenttracks']['track']) == 1:
context.responses.append(await context.send(
f'{member.display_name} is not listening to anything...'))
await context.send(f'{member.display_name} is not listening to anything...')

else:
track = recent_tracks['recenttracks']['track'][0]
@@ -79,7 +75,7 @@ class LastFM(commands.Cog):
track['artist']['#text'])

file = discord.File(image, filename='img.png')
context.responses.append(await context.send(file=file))
await context.send(file=file)

async def fetch_recent_tracks(self, username, limit=1):
parameters = {
@@ -156,11 +152,10 @@ class LastFM(commands.Cog):

if user:
await self.users.update_user(user['id'], username)
context.responses.append(await
context.send('Username has been updated'))
await context.send('Username has been updated')
else:
await self.users.insert_user(context.author.id, username)
context.responses.append(await context.send('Username set!'))
await context.send('Username set!')


def setup(bot):

+ 7
- 9
cogs/misc.py 查看文件

@@ -14,14 +14,14 @@ class Misc(commands.Cog):
phrase = self.get_phrase(message)
if phrase:
response = await message.channel.send(phrase)
await self.bot.register_response(response, message)
await self.bot.register_response(message, response)

@commands.Cog.listener()
async def on_message_edit(self, before, after):
phrase = self.get_phrase(after)
if phrase:
response = await after.channel.send(phrase)
await self.bot.register_response(response, after)
await self.bot.register_response(after, response)

def get_phrase(self, message):
lower_content = message.content.lower()
@@ -43,10 +43,9 @@ class Misc(commands.Cog):
async def play(self, context, song: str):
"""I'll play you a song!"""
if song == 'despacito':
context.responses.append(await context.send('Fakku no!'))
await context.send('Fakku no!')
else:
context.responses.append(
await context.send('I don\'t know that song yet...'))
await context.send('I don\'t know that song yet...')

@commands.command()
async def info(self, context):
@@ -55,7 +54,7 @@ class Misc(commands.Cog):
title="Info~", description=f"My owner is {str(self.bot.owner)}!")
embed.set_author(
name=self.bot.user.name, icon_url=self.bot.user.avatar_url)
context.responses.append(await context.send(embed=embed))
await context.send(embed=embed)

@commands.command(aliases=['up'])
async def uptime(self, context):
@@ -63,14 +62,13 @@ class Misc(commands.Cog):

delta = datetime.datetime.utcnow() - self.bot.started_on
delta = datetime.timedelta(delta.days, delta.seconds)
context.responses.append(await
context.send(f"Online for {str(delta)}"))
await context.send(f"Online for {str(delta)}")

@commands.command(aliases=['pat'])
async def pet(self, context):
"""Give pets"""

context.responses.append(await context.send("No touching!"))
await context.send("No touching!")


def setup(bot):

+ 1
- 1
cogs/template.py 查看文件

@@ -9,7 +9,7 @@ class Template(commands.Cog):

@commands.command()
async def template(self, context):
context.responses.append(context.send('This is a template desu!'))
context.send('This is a template desu!')


def setup(bot):

+ 16
- 13
utils/sorachan.py 查看文件

@@ -5,6 +5,11 @@ from discord.ext import commands
from utils import config
from utils import redis

class Context(commands.Context):
async def send(self, content=None, **kwargs):
message = await super().send(content, **kwargs)
await self.bot.register_response(self.message, message)
return message

class Sorachan(commands.Bot):
def __init__(self):
@@ -14,8 +19,6 @@ class Sorachan(commands.Bot):
self.pg = None
self.owner = None
self.load_extension('cogs.admin')
self.before_invoke(self.prepare_context)
self.after_invoke(self.register_responses)

async def on_connect(self):
if not self.redis:
@@ -41,6 +44,13 @@ class Sorachan(commands.Bot):
await self.track_message(f'tracked_message {message.id}')
await self.process_commands(message)

async def process_commands(self, message):
if message.author.bot:
return

ctx = await self.get_context(message, cls=Context)
await self.invoke(ctx)

async def on_raw_bulk_message_delete(self, payload):
for message_id in payload.message_ids:
await self.delete_responses(message_id)
@@ -49,9 +59,9 @@ class Sorachan(commands.Bot):
await self.delete_responses(payload.message_id)

async def delete_responses(self, message_id):
if await self.redis.exists(message_id):
await self.clear_responses(message_id)
await self.redis.delete(message_id)
if await self.redis.exists(f'tracked_message {message_id}'):
await self.clear_responses(f'tracked_message {message_id}')
await self.redis.delete(f'tracked_message {message_id}')

async def on_raw_message_edit(self, payload):
if 'content' not in payload.data:
@@ -89,13 +99,6 @@ class Sorachan(commands.Bot):
await self.pg.close()
await super().close()

async def prepare_context(self, context):
context.responses = []

async def register_responses(self, context):
for message in context.responses:
await self.register_response(message, context.message)

async def track_message(self, message):
if await self.redis.exists(message):
return
@@ -103,7 +106,7 @@ class Sorachan(commands.Bot):
await self.redis.rpush(message, 0)
await self.redis.expire(message, 3600)

async def register_response(self, response, request):
async def register_response(self, request, response):
if await self.redis.exists(f'tracked_message {request.id}'):
await self.redis.rpush(f'tracked_message {request.id}',
f'{response.channel.id}:{response.id}')

+ 5
- 2
utils/sorahelp.py 查看文件

@@ -14,7 +14,7 @@ class SoraHelpCommand(commands.HelpCommand):
embed.description = command.short_doc or 'No description'
embed.set_footer(text=f'Category: {command.cog_name}')
destination = self.get_destination()
self.context.responses.append(await destination.send(embed=embed))
await destination.send(embed=embed)

# todo: fix layout whenever I actually add some group commands
async def send_group_help(self, group):
@@ -61,6 +61,9 @@ class SoraHelpCommand(commands.HelpCommand):
self.add_command_field(embedinator, command)

await self.send_embedinator(embedinator)
def get_destination(self):
return self.context

def command_not_found(self, string):
return f'Command or category "{string}" not found.'
@@ -109,6 +112,6 @@ class SoraHelpCommand(commands.HelpCommand):
embedinator.add_field(name=name, value=command.short_doc, inline=False)

async def send_embedinator(self, embedinator):
self.context.responses.append(await embedinator.send())
await embedinator.send()
if len(embedinator.embed_list) != 1:
await embedinator.handle()

正在加载...
取消
保存