Skip to content

Commit

Permalink
Merge pull request #11696 from PennyDreadfulMTG/i.py
Browse files Browse the repository at this point in the history
Bump to latest version of the interactions.py
  • Loading branch information
mergify[bot] authored Oct 4, 2023
2 parents bb8401c + fcdff13 commit 1a544b5
Show file tree
Hide file tree
Showing 57 changed files with 942 additions and 869 deletions.
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ sentry-sdk = {extras = ["flask"], version = "*"}
pydantic = "*"
pystache = "*"
fasteners = "*"
naff = "==2.1.0"
"interactions.py" = "==5.6.0"
tomli = "*"
orjson = "*"
traceback-with-variables = "*"
Expand Down
1,434 changes: 730 additions & 704 deletions Pipfile.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,10 @@ def reset_db() -> None:
def dev_db() -> None:
# reset_db()
print('>>>> Downloading dev db')
import requests
import gzip

import requests

import decksite.database
r = requests.get('https://pennydreadfulmagic.com/static/dev-db.sql.gz')
r.raise_for_status()
Expand Down
10 changes: 5 additions & 5 deletions discordbot/background.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
import os
import sys

from naff import MISSING, Absent, Client, Extension, listen
from naff.client.errors import Forbidden
from naff.client.utils import timestamp_converter
from naff.models.discord import Embed, GuildText, ScheduledEventType
from naff.models.naff.tasks import IntervalTrigger, Task
from interactions import MISSING, Absent, Client, Extension, listen
from interactions.client.errors import Forbidden
from interactions.client.utils import timestamp_converter
from interactions.models.discord import Embed, GuildText, ScheduledEventType
from interactions.models.internal.tasks import IntervalTrigger, Task

from magic import fetcher, image_fetcher, multiverse, rotation, seasons, tournaments
from shared import configuration, dtutil, fetch_tools, redis_wrapper, repo
Expand Down
24 changes: 13 additions & 11 deletions discordbot/bot.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import asyncio
import logging
import subprocess
from typing import Any, Dict, List, Optional, cast
from typing import Any, Dict, List, Optional

from naff import Client, listen
from naff.api.events import MemberAdd, MessageCreate, MessageReactionAdd, PresenceUpdate
from naff.models import ActivityType, Guild, GuildText, Intents, Member, Role
from interactions import Client, listen
from interactions.api.events import MemberAdd, MessageCreate, MessageReactionAdd, PresenceUpdate
from interactions.ext import prefixed_commands
from interactions.models import ActivityType, Guild, GuildText, Intents, Member, Role

import discordbot.commands
from discordbot import command
Expand All @@ -23,19 +24,20 @@ def __init__(self, **kwargs: Any) -> None:
commit_id = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode()
redis.store('discordbot:commit_id', commit_id)

intents = Intents(Intents.DEFAULT | Intents.MESSAGES | Intents.GUILD_PRESENCES | Intents.GUILD_MESSAGE_CONTENT)
intents = Intents(Intents.DEFAULT | Intents.MESSAGES | Intents.GUILD_PRESENCES | Intents.MESSAGE_CONTENT)

super().__init__(intents=intents, sync_interactions=True, delete_unused_application_cmds=True, default_prefix='!',
prefixed_context=command.MtgMessageContext, interaction_context=command.MtgInteractionContext,
super().__init__(intents=intents, sync_interactions=True, delete_unused_application_cmds=True,
interaction_context=command.MtgInteractionContext,
**kwargs)
prefixed_commands.setup(self, prefixed_context=command.MtgMessageContext, default_prefix='!')
self.achievement_cache: Dict[str, Dict[str, str]] = {}
discordbot.commands.setup(self)
if configuration.bot_debug.value:
self.load_extension('naff.ext.debug_extension')
self.load_extension('naff.ext.jurigged')
self.load_extension('interactions.ext.debug_extension')
self.load_extension('interactions.ext.jurigged')
self.sentry_token = configuration.get_optional_str('sentry_token')
if self.sentry_token:
self.load_extension('naff.ext.sentry', token=self.sentry_token)
self.load_extension('interactions.ext.sentry', token=self.sentry_token)
self.load_extension('discordbot.background')

async def stop(self) -> None:
Expand All @@ -59,7 +61,7 @@ async def on_message_create(self, event: MessageCreate) -> None:
if event.message.channel is None:
logging.warn(f'Got Message with no channel: {event.message}')

ctx = cast(command.MtgMessageContext, await self.get_context(event.message)) # Casting, because we overrode the base class
ctx = command.MtgMessageContext.from_message(self, event.message)
await command.respond_to_card_names(ctx)

@listen()
Expand Down
24 changes: 12 additions & 12 deletions discordbot/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@

import attr
import whoosh
from naff import CMD_BODY, DM, Client, DMGroup
from naff.client.errors import Forbidden
from naff.models import (TYPE_MESSAGEABLE_CHANNEL, AutocompleteContext, ChannelTypes, Extension,
File, InteractionCommand, InteractionContext, Member, Message,
OptionTypes, PrefixedCommand, PrefixedContext, User, prefixed_command,
slash_option)
from interactions import Client
from interactions.client.errors import Forbidden
from interactions.ext.prefixed_commands import PrefixedCommand, PrefixedContext, prefixed_command
from interactions.models import (DM, TYPE_MESSAGEABLE_CHANNEL, AutocompleteContext, ChannelType,
DMGroup, Extension, File, InteractionCommand, InteractionContext,
Member, Message, OptionType, User, slash_option)

from discordbot import emoji
from discordbot.shared import channel_id, guild_id
Expand Down Expand Up @@ -43,7 +43,7 @@ async def respond_to_card_names(ctx: 'MtgMessageContext') -> None:
# Don't parse messages with Gatherer URLs because they use square brackets in the querystring.
if 'gatherer.wizards.com' in ctx.message.content.lower():
return
compat = False and ctx.channel.type == ChannelTypes.GUILD_TEXT and await ctx.bot.get_user(268547439714238465) in ctx.channel.members # see #7074
compat = False and ctx.channel.type == ChannelType.GUILD_TEXT and await ctx.bot.get_user(268547439714238465) in ctx.channel.members # see #7074
queries = parse_queries(ctx.message.content, compat)
if len(queries) > 0:
try:
Expand Down Expand Up @@ -213,7 +213,7 @@ def wrapper(func: Callable) -> Callable:
name=param,
description='Name of a Card',
required=True,
opt_type=OptionTypes.STRING,
opt_type=OptionType.STRING,
autocomplete=False,
)(func)

Expand All @@ -227,7 +227,7 @@ def wrapper(func: Callable) -> Callable:

# return wrapper

def make_choice(value: str, name: Optional[str] = None) -> Dict[str, str]:
def make_choice(value: str, name: Optional[str] = None) -> Dict[str, Union[int, float, str]]:
return {
'name': (name or value)[:100],
'value': value[:100],
Expand All @@ -244,7 +244,7 @@ async def autocomplete_card(scale: Extension, ctx: AutocompleteContext, card: st
choices.extend(results.other_prefixed)
choices.extend(results.fuzzy)
choices = [*set(choices)]
await ctx.send(choices=list(make_choice(c) for c in choices[:20])) # type: ignore
await ctx.send(choices=list(make_choice(c) for c in choices[:20]))

def migrate_to_slash_command(command: InteractionCommand, soft: bool = False) -> PrefixedCommand:
"""
Expand All @@ -266,11 +266,11 @@ def alias_message_command_to_slash_command(command: InteractionCommand, param: s
This is a horrible hack. Use it if a slash command takes one multiword argument
"""

async def wrapper(_scale: Extension, ctx: MtgMessageContext, body: CMD_BODY) -> None:
async def wrapper(_scale: Extension, ctx: MtgMessageContext) -> None:
if nag:
await ctx.reply(f'This command has been updated. Please use {command.mention()} instead.')

ctx.kwargs[param] = body
ctx.kwargs[param] = ctx.content_parameters
await command.call_callback(command.callback, ctx)

if name is None:
Expand Down
19 changes: 9 additions & 10 deletions discordbot/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import inspect
import logging
from os import path
from typing import Optional
from typing import Optional, cast

from naff import Client
from naff.models import Extension, InteractionCommand, PrefixedCommand, SendableContext
from interactions import Client, SlashContext
from interactions.ext.prefixed_commands import (PrefixedCommand, PrefixedContext,
PrefixedInjectedClient)
from interactions.models import InteractionCommand

from discordbot import command
from magic.models import Card
Expand Down Expand Up @@ -34,19 +36,16 @@ def scaleless_load(bot: Client, module: str) -> bool:
bot.add_interaction(obj)
n += 1
elif isinstance(obj, PrefixedCommand):
bot.add_prefixed_command(obj)
n += 1
elif isinstance(obj, Extension):
logging.warning(f'{module} is an Extension, but it doesnt have a setup method')
obj(bot) # type: ignore
botp = cast(PrefixedInjectedClient, bot)
botp.prefixed.add_command(obj)
n += 1
except Exception:
pass
raise
return n > 0

class CardConverter:
@classmethod
async def convert(cls, ctx: SendableContext, argument: str) -> Optional[Card]:
async def convert(cls, ctx: PrefixedContext | SlashContext, argument: str) -> Optional[Card]:
try:
result, mode, printing = command.results_from_queries([argument])[0]
if result.has_match() and not result.is_ambiguous():
Expand Down
4 changes: 2 additions & 2 deletions discordbot/commands/art.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re

from naff.client import Client
from naff.models import Extension, slash_command
from interactions.client import Client
from interactions.models import Extension, slash_command

from discordbot import command
from discordbot.command import MtgInteractionContext
Expand Down
3 changes: 2 additions & 1 deletion discordbot/commands/barbs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

from naff import Client, Extension, prefixed_command
from interactions import Client, Extension
from interactions.ext.prefixed_commands import prefixed_command

from discordbot.command import MtgMessageContext

Expand Down
12 changes: 6 additions & 6 deletions discordbot/commands/bug.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
from typing import Optional

from naff import Client, Extension
from naff.models import OptionTypes, slash_command, slash_option
from interactions import Client, Extension
from interactions.models import OptionType, slash_command, slash_option

from discordbot.command import MtgContext
from shared import repo


class Bug(Extension):
@slash_command('bug')
@slash_option('title', 'One sentence description of the issue', OptionTypes.STRING, required=True)
@slash_option('body', 'More info', OptionTypes.STRING)
@slash_option('title', 'One sentence description of the issue', OptionType.STRING, required=True)
@slash_option('body', 'More info', OptionType.STRING)
async def bug(self, ctx: MtgContext, title: str, body: Optional[str] = None) -> None:
"""Report a bug/task for the Penny Dreadful Tools team. For Magic Online bugs see `/modobug`."""
text = title
Expand All @@ -23,8 +23,8 @@ async def bug(self, ctx: MtgContext, title: str, body: Optional[str] = None) ->
await ctx.send('Issue has been reported at <{url}>'.format(url=issue.html_url))

@slash_command('gbug')
@slash_option('title', 'One sentence description of the issue', OptionTypes.STRING, required=True)
@slash_option('body', 'More info', OptionTypes.STRING)
@slash_option('title', 'One sentence description of the issue', OptionType.STRING, required=True)
@slash_option('body', 'More info', OptionType.STRING)
async def gatherlingbug(self, ctx: MtgContext, title: str, body: Optional[str] = None) -> None:
"""Report a Gatherling bug."""
text = title
Expand Down
2 changes: 1 addition & 1 deletion discordbot/commands/burningofxinye.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from naff.models import prefixed_command
from interactions.ext.prefixed_commands import prefixed_command

from discordbot.command import MtgContext

Expand Down
6 changes: 3 additions & 3 deletions discordbot/commands/clearimagecache.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import glob
import os

from naff import check, is_owner
from naff.models import slash_command
from interactions import check, is_owner
from interactions.models import slash_command

from discordbot.command import MtgContext
from shared import configuration


@slash_command('clearimagecache') # type: ignore
@slash_command('clearimagecache')
@check(is_owner())
async def clearimagecache(ctx: MtgContext) -> None:
"""Deletes all the cached images. Use sparingly"""
Expand Down
12 changes: 6 additions & 6 deletions discordbot/commands/configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import traceback
from typing import Any, Optional

from naff import User
from naff.client.errors import CommandException
from naff.models import slash_command
from interactions import User
from interactions.client.errors import CommandException
from interactions.models import slash_command

from discordbot.command import MtgContext
from shared import settings
Expand All @@ -20,13 +20,13 @@ async def configure(ctx: MtgContext, scope: str, setting: str) -> None:
if isinstance(ctx.author, User):
await ctx.send("Can't configure DMs right now, sorry")
return
if not ctx.author.guild_permissions.manage_channels:
if not ctx.author.guild_permissions.MANAGE_CHANNELS:
await ctx.send("You don't have permsssion to configure this server.")
return
if scope == 'channel':
configuring = ctx.channel.id
elif scope in ['server', 'guild']:
configuring = ctx.channel.guild.id
configuring = ctx.channel.guild.id # type: ignore
else:
await ctx.send('You need to configure one of `server` or `channel`.')
return
Expand All @@ -39,7 +39,7 @@ async def configure(ctx: MtgContext, scope: str, setting: str) -> None:
raise ConfigError(configuring)

with settings.with_config_file(configuring):
settings.SETTINGS[key].set(value)
settings.SETTINGS[key].set(value) # type: ignore

@configure.error
async def configure_error(ctx: MtgContext, error: Exception) -> None:
Expand Down
15 changes: 8 additions & 7 deletions discordbot/commands/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
Debug stuff
"""

from naff import Extension, prefixed_command
from naff.client import Client
from naff.client.errors import CommandCheckFailure, ExtensionLoadException
from naff.models import PrefixedContext, check, is_owner
from interactions import Extension
from interactions.client import Client
from interactions.client.errors import CommandCheckFailure, ExtensionLoadException
from interactions.ext.prefixed_commands import PrefixedContext, prefixed_command
from interactions.models import check, is_owner


class PDDebug(Extension):
@prefixed_command('regrow') # type: ignore
@prefixed_command('regrow')
@check(is_owner())
async def regrow(self, ctx: PrefixedContext, module: str) -> None:
try:
Expand All @@ -32,10 +33,10 @@ async def regrow_error(self, error: Exception, ctx: PrefixedContext) -> None:
return
raise

@prefixed_command('enable_debugger') # type: ignore
@prefixed_command('enable_debugger')
@check(is_owner())
async def enable_debugger(self, ctx: PrefixedContext) -> None:
self.bot.load_extension('naff.ext.debug_extension')
self.bot.load_extension('interactions.ext.debug_extension')
await self.bot.synchronise_interactions()
await ctx.send('Enabled')

Expand Down
3 changes: 2 additions & 1 deletion discordbot/commands/downtimes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from naff.models import prefixed_command, slash_command
from interactions.ext.prefixed_commands import prefixed_command
from interactions.models import slash_command

from discordbot.command import MtgContext
from magic import fetcher
Expand Down
10 changes: 5 additions & 5 deletions discordbot/commands/drc.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Dict, Optional
from urllib import parse

from naff.models import Embed, OptionTypes, slash_command, slash_option
from interactions.models import Embed, OptionType, slash_command, slash_option

from discordbot.command import (DEFAULT_CARDS_SHOWN, MAX_CARDS_SHOWN, MtgContext,
MtgInteractionContext)
Expand Down Expand Up @@ -36,7 +36,7 @@ async def drc(ctx: MtgContext) -> None:
...

@drc.subcommand('search', sub_cmd_description='Card Search using Dreadrise')
@slash_option('query', 'search query', OptionTypes.STRING, required=True)
@slash_option('query', 'search query', OptionType.STRING, required=True)
async def cardsearch(ctx: MtgInteractionContext, query: str) -> None:
"""Card search using Dreadrise."""
await ctx.defer()
Expand All @@ -59,7 +59,7 @@ async def cardsearch(ctx: MtgInteractionContext, query: str) -> None:
await ctx.post_cards(cards, ctx.author, more_results_link(query, count))

@drc.subcommand('deck')
@slash_option('query', 'search query', OptionTypes.STRING, required=True)
@slash_option('query', 'search query', OptionType.STRING, required=True)
async def decks(ctx: MtgInteractionContext, query: str) -> None:
"""Deck search using Dreadrise."""
await ctx.defer()
Expand Down Expand Up @@ -93,8 +93,8 @@ async def decks(ctx: MtgInteractionContext, query: str) -> None:
await ctx.send(embeds=[embed])

@drc.subcommand('matchups')
@slash_option('q1', 'The query for the first player', OptionTypes.STRING, required=True)
@slash_option('q2', 'The query for the second player', OptionTypes.STRING, required=False)
@slash_option('q1', 'The query for the first player', OptionType.STRING, required=True)
@slash_option('q2', 'The query for the second player', OptionType.STRING, required=False)
async def matchups(ctx: MtgInteractionContext, q1: str, q2: Optional[str]) -> None:
"""Matchup calculation using Dreadrise."""
await ctx.defer()
Expand Down
Loading

0 comments on commit 1a544b5

Please sign in to comment.