Skip to content

Commit

Permalink
Merge pull request #155 from onerandomusername/migrate-to-disnake
Browse files Browse the repository at this point in the history
feat: migrate to disnake and dpy 2.0
  • Loading branch information
Akarys42 authored Jan 2, 2022
2 parents 840e150 + 7ab5b70 commit 561dffa
Show file tree
Hide file tree
Showing 29 changed files with 574 additions and 423 deletions.
8 changes: 5 additions & 3 deletions bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import asyncpg
from aiohttp import ClientSession
from bot.postgres import create_tables
from discord import AllowedMentions, Embed, Intents, Object
from discord.ext import commands
from disnake import AllowedMentions, Embed, Intents, Object
from disnake.ext import commands
from loguru import logger

from . import constants
Expand Down Expand Up @@ -105,7 +105,9 @@ async def startup_greeting(self) -> None:
"""Announce presence to the devlog channel."""
embed = Embed(description="Connected!")
embed.set_author(
name="Gurkbot", url=constants.BOT_REPO_URL, icon_url=self.user.avatar_url
name="Gurkbot",
url=constants.BOT_REPO_URL,
icon_url=self.user.display_avatar.url,
)
await self.get_channel(constants.Channels.devlog).send(embed=embed)

Expand Down
2 changes: 1 addition & 1 deletion bot/converters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from discord.ext.commands import BadArgument, Context, Converter
from disnake.ext.commands import BadArgument, Context, Converter


class OffTopicName(Converter):
Expand Down
8 changes: 4 additions & 4 deletions bot/exts/backend/error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import random
from typing import Optional

import discord
import disnake
from bot.constants import Channels, Colours, ERROR_REPLIES
from discord import Embed, Message
from discord.ext import commands
from disnake import Embed, Message
from disnake.ext import commands
from loguru import logger


Expand Down Expand Up @@ -140,7 +140,7 @@ async def handle_unexpected_error(
)
try:
dev_alerts = await self.bot.fetch_channel(Channels.devalerts)
except discord.HTTPException as discord_exc:
except disnake.HTTPException as discord_exc:
logger.exception("Fetch failed", exc_info=discord_exc)
return

Expand Down
10 changes: 5 additions & 5 deletions bot/exts/fun/bonker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from io import BytesIO
from typing import Dict

import discord
import disnake
from PIL import Image, ImageDraw, ImageFile, ImageSequence
from discord.ext import commands
from disnake.ext import commands
from loguru import logger

ImageFile.LOAD_TRUNCATED_IMAGES = True
Expand Down Expand Up @@ -97,9 +97,9 @@ def _generate_gif(self, pfp: bytes) -> BytesIO:

@commands.command()
@commands.max_concurrency(3)
async def bonk(self, ctx: commands.Context, member: discord.User) -> None:
async def bonk(self, ctx: commands.Context, member: disnake.User) -> None:
"""Sends gif of mentioned member being "bonked" by Yoda."""
pfp = await member.avatar_url.read()
pfp = await member.display_avatar.read()
created_at = ctx.message.created_at.strftime("%Y-%m-%d_%H-%M")
out_filename = f"bonk_{member.id}_{created_at}.gif"
func = functools.partial(self._generate_gif, pfp)
Expand All @@ -109,7 +109,7 @@ async def bonk(self, ctx: commands.Context, member: discord.User) -> None:
out_gif = await asyncio.get_running_loop().run_in_executor(pool, func)

out_gif.seek(0)
await ctx.send(file=discord.File(out_gif, out_filename))
await ctx.send(file=disnake.File(out_gif, out_filename))


def setup(bot: commands.Bot) -> None:
Expand Down
4 changes: 2 additions & 2 deletions bot/exts/fun/ciphers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from bot.bot import Bot
from bot.constants import Colours
from discord import Embed
from discord.ext.commands import BadArgument, Cog, Context, group
from disnake import Embed
from disnake.ext.commands import BadArgument, Cog, Context, group

logger = logging.getLogger(__name__)

Expand Down
6 changes: 3 additions & 3 deletions bot/exts/fun/off_topic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
from bot.converters import OffTopicName as OT_Converter
from bot.postgres.utils import db_execute, db_fetch
from bot.utils.pagination import LinePaginator
from discord import Embed, Reaction, TextChannel, User
from discord.ext.commands import Cog, Context, group, has_any_role
from discord.utils import sleep_until
from disnake import Embed, Reaction, TextChannel, User
from disnake.ext.commands import Cog, Context, group, has_any_role
from disnake.utils import sleep_until
from fuzzywuzzy import fuzz
from loguru import logger

Expand Down
6 changes: 3 additions & 3 deletions bot/exts/fun/xkcd.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@

from bot.bot import Bot
from bot.constants import Colours
from discord import Embed
from discord.ext import tasks
from discord.ext.commands import Cog, Context, command
from disnake import Embed
from disnake.ext import tasks
from disnake.ext.commands import Cog, Context, command

log = logging.getLogger(__name__)

Expand Down
18 changes: 9 additions & 9 deletions bot/exts/github/_issues.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from random import choice
from typing import Optional

import discord
import disnake
from aiohttp import ClientSession
from bot.constants import Channels, ERROR_REPLIES, Emojis
from discord import Embed
from discord.ext import commands
from disnake import Embed
from disnake.ext import commands
from loguru import logger

BAD_RESPONSE = {
Expand All @@ -28,23 +28,23 @@ def __init__(self, http_session: ClientSession) -> None:
self.http_session = http_session

@staticmethod
def get_repo(channel: discord.TextChannel) -> Optional[str]:
def get_repo(channel: disnake.TextChannel) -> Optional[str]:
"""Get repository for the particular channel."""
return REPO_CHANNEL_MAP.get(channel.id, "gurkbot")

@staticmethod
def error_embed(error_msg: str) -> Embed:
"""Generate Error Embed for Issues command."""
embed = discord.Embed(
embed = disnake.Embed(
title=choice(ERROR_REPLIES),
color=discord.Color.red(),
color=disnake.Color.red(),
description=error_msg,
)
return embed

async def issue(
self,
channel: discord.TextChannel,
channel: disnake.TextChannel,
numbers: commands.Greedy[int],
repository: Optional[str],
user: str,
Expand Down Expand Up @@ -104,8 +104,8 @@ async def issue(
)
)

resp = discord.Embed(
colour=discord.Color.green(),
resp = disnake.Embed(
colour=disnake.Color.green(),
description="\n".join("{0} [{1}]({2})".format(*link) for link in links),
)
resp.set_author(name="GitHub", url=f"https://github.com/{user}/{repository}")
Expand Down
12 changes: 6 additions & 6 deletions bot/exts/github/_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from random import choice
from typing import Optional

import discord
import disnake
from aiohttp import ClientSession
from bot.constants import ERROR_REPLIES
from discord import Embed
from disnake import Embed


class GithubInfo:
Expand Down Expand Up @@ -33,12 +33,12 @@ def get_data(username: Optional[str], user_data: dict, org_data: dict) -> Embed:
else:
blog = "-"

embed = discord.Embed(
embed = disnake.Embed(
title=f"{user_data['login']}'s GitHub profile info",
description=f"```{user_data['bio']}```\n"
if user_data["bio"] is not None
else "",
colour=discord.Colour.green(),
colour=disnake.Colour.green(),
url=user_data["html_url"],
timestamp=datetime.strptime(
user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ"
Expand Down Expand Up @@ -76,11 +76,11 @@ async def get_github_info(self, username: str) -> Embed:

# User_data will not have a message key if the user exists
if user_data.get("message") is not None:
embed = discord.Embed(
embed = disnake.Embed(
title=choice(ERROR_REPLIES),
description=f"The profile for `{username}` was not found.",
url=Embed.Empty,
colour=discord.Colour.red(),
colour=disnake.Colour.red(),
)
return embed

Expand Down
10 changes: 5 additions & 5 deletions bot/exts/github/_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from textwrap import dedent
from typing import Optional

import discord
import disnake
from aiohttp import ClientSession
from bot import constants
from discord.ext.commands import Command
from disnake.ext.commands import Command

doc_reg_class = r'("""|\'\'\')([\s\S]*?)(\1\s*)'

Expand All @@ -15,13 +15,13 @@ class Source:
"""Displays information about the bot's source code."""

def __init__(
self, http_session: ClientSession, bot_avatar: discord.asset.Asset
self, http_session: ClientSession, bot_avatar: disnake.asset.Asset
) -> None:
self.http_session = http_session
self.MAX_FIELD_LENGTH = 500
self.bot_avatar = bot_avatar

async def inspect(self, cmd: Optional[Command]) -> Optional[discord.Embed]:
async def inspect(self, cmd: Optional[Command]) -> Optional[disnake.Embed]:
"""Display information and a GitHub link to the source code of a command."""
if cmd is None:
return
Expand All @@ -48,7 +48,7 @@ async def inspect(self, cmd: Optional[Command]) -> Optional[discord.Embed]:
+ "\n... (truncated - too many lines)"
)

embed = discord.Embed(title="Gurkbot's Source Link", description=f"{url}")
embed = disnake.Embed(title="Gurkbot's Source Link", description=f"{url}")
embed.add_field(
name="Source Code Snippet", value=f"```python\n{sanitized}\n```"
)
Expand Down
12 changes: 7 additions & 5 deletions bot/exts/github/github.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import typing

from bot.constants import BOT_REPO_URL
from discord import Embed
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from disnake import Embed
from disnake.ext import commands
from disnake.ext.commands.cooldowns import BucketType

from . import _issues, _profile, _source

Expand Down Expand Up @@ -71,15 +71,17 @@ async def source_command(
if source_item is None:
embed = Embed(title="Gurkbot's GitHub Repository")
embed.add_field(name="Repository", value=f"[Go to GitHub]({BOT_REPO_URL})")
embed.set_thumbnail(url=self.bot.user.avatar_url)
embed.set_thumbnail(url=self.bot.user.display_avatar.url)
await ctx.send(embed=embed)
return
elif not ctx.bot.get_command(source_item):
raise commands.BadArgument(
f"Unable to convert `{source_item}` to valid command or Cog."
)

github_source = _source.Source(self.bot.http_session, self.bot.user.avatar_url)
github_source = _source.Source(
self.bot.http_session, self.bot.user.display_avatar.url
)
embed = await github_source.inspect(cmd=ctx.bot.get_command(source_item))

await ctx.send(embed=embed)
Expand Down
4 changes: 2 additions & 2 deletions bot/exts/gurkan/gurkan_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from bot.bot import Bot
from bot.constants import Emojis
from bot.utils.is_gurkan import gurkan_check, gurkan_rate
from discord import Color, Embed, Member
from discord.ext.commands import Cog, Context, command
from disnake import Color, Embed, Member
from disnake.ext.commands import Cog, Context, command


RATE_DICT = {
Expand Down
4 changes: 2 additions & 2 deletions bot/exts/gurkan/gurkify.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from bot.bot import Bot
from bot.constants import Colours, GurkanNameEndings, NEGATIVE_REPLIES, POSITIVE_REPLIES
from bot.utils.is_gurkan import gurkan_check
from discord import Embed, Forbidden
from discord.ext import commands
from disnake import Embed, Forbidden
from disnake.ext import commands


class Gurkify(commands.Cog):
Expand Down
10 changes: 5 additions & 5 deletions bot/exts/gurkan/make_gurkan.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import discord
import disnake
from bot.bot import Bot
from bot.constants import Roles
from bot.utils.is_gurkan import gurkan_check
from discord.ext import commands
from discord.utils import get
from disnake.ext import commands
from disnake.utils import get


class MakeGurkan(commands.Cog):
Expand All @@ -14,7 +14,7 @@ def __init__(self, bot: Bot) -> None:

@commands.Cog.listener()
async def on_member_update(
self, before: discord.Member, after: discord.Member
self, before: disnake.Member, after: disnake.Member
) -> None:
"""
Adds/Removes the gurkan role on member update.
Expand All @@ -34,7 +34,7 @@ async def on_member_update(
await after.remove_roles(role)

@commands.Cog.listener()
async def on_member_join(self, member: discord.Member) -> None:
async def on_member_join(self, member: disnake.Member) -> None:
"""Adds the gurkan role to new members who are classified as gurkans."""
if member.bot:
return
Expand Down
10 changes: 5 additions & 5 deletions bot/exts/gurkcraft/gurkcraft.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from typing import Optional

import discord
import disnake
from bot.constants import Channels, Colours, Minecraft
from discord import Embed, TextChannel
from discord.ext import commands, tasks
from discord.ext.commands import Bot
from disnake import Embed, TextChannel
from disnake.ext import commands, tasks
from disnake.ext.commands import Bot
from loguru import logger
from mcstatus import MinecraftServer

Expand Down Expand Up @@ -42,7 +42,7 @@ async def mcstatus(self, ctx: commands.Context) -> None:
return
players = _extract_users(status)

embed = discord.Embed(title="Gurkcraft", color=Colours.green)
embed = disnake.Embed(title="Gurkcraft", color=Colours.green)
embed.add_field(name="Server", value="mc.gurkult.com")
embed.add_field(name="Server Latency", value=f"{status.latency}ms")
embed.add_field(name="Gurkans Online", value=status.players.online)
Expand Down
8 changes: 4 additions & 4 deletions bot/exts/moderation/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from bot.bot import Bot
from bot.constants import Channels, Colours
from discord import Embed, Member, Message, RawMessageDeleteEvent, TextChannel, User
from discord.ext.commands import Cog
from disnake import Embed, Member, Message, RawMessageDeleteEvent, TextChannel, User
from disnake.ext.commands import Cog
from loguru import logger


Expand Down Expand Up @@ -68,7 +68,7 @@ async def post_formatted_message(
description=body or "<no additional information provided>",
colour=colour,
timestamp=datetime.utcnow(),
).set_thumbnail(url=actor.avatar_url)
).set_thumbnail(url=actor.display_avatar.url)

if link:
embed.url = link
Expand Down Expand Up @@ -160,7 +160,7 @@ async def on_message(self, message: Message) -> None:
description=message.content,
colour=Colours.green,
timestamp=datetime.utcnow(),
).set_thumbnail(url=message.author.avatar_url)
).set_thumbnail(url=message.author.display_avatar.url)
)


Expand Down
Loading

0 comments on commit 561dffa

Please sign in to comment.