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

hot fix and add black -> ruff #111

Merged
merged 4 commits into from
Apr 19, 2024
Merged
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
22 changes: 12 additions & 10 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ class ValorantBot(commands.Bot):

def __init__(self) -> None:
super().__init__(command_prefix=BOT_PREFIX, case_insensitive=True, intents=intents)
self.session: aiohttp.ClientSession = None
self.session: aiohttp.ClientSession | None = None
self.bot_version = '3.3.5'
self.tree.interaction_check = self.interaction_check

@staticmethod
async def interaction_check(interaction: discord.Interaction) -> bool:
locale_v2.set_interaction_locale(interaction.locale) # bot responses localized # wait for update
locale_v2.set_valorant_locale(interaction.locale) # valorant localized
locale_v2.set_interaction_locale(interaction.locale) # bot responses localized # wait for update # type: ignore
locale_v2.set_valorant_locale(interaction.locale) # valorant localized # type: ignore
return True

@property
Expand All @@ -49,19 +49,19 @@ def owner(self) -> discord.User:

async def on_ready(self) -> None:
await self.tree.sync()
print(f"\nLogged in as: {self.user}\n\n BOT IS READY !")
print(f"Version: {self.bot_version}")
print(f'\nLogged in as: {self.user}\n\n BOT IS READY !')
print(f'Version: {self.bot_version}')

# bot presence
activity_type = discord.ActivityType.listening
await self.change_presence(activity=discord.Activity(type=activity_type, name="(╯•﹏•╰)"))
await self.change_presence(activity=discord.Activity(type=activity_type, name='(╯•﹏•╰)'))

async def setup_hook(self) -> None:
if self.session is None:
self.session = aiohttp.ClientSession()

try:
self.owner_id = int(os.getenv('OWNER_ID'))
self.owner_id = int(os.getenv('OWNER_ID')) # type: ignore
except ValueError:
self.bot_app_info = await self.application_info()
self.owner_id = self.bot_app_info.owner.id
Expand All @@ -85,17 +85,19 @@ async def load_cogs(self) -> None:
@staticmethod
def setup_cache() -> None:
try:
open('data/cache.json')
with open('data/cache.json'):
...
except FileNotFoundError:
get_cache()

async def close(self) -> None:
await self.session.close()
if self.session:
await self.session.close()
await super().close()

async def start(self, debug: bool = False) -> None:
self.debug = debug
return await super().start(os.getenv('TOKEN'), reconnect=True)
return await super().start(os.getenv('TOKEN'), reconnect=True) # type: ignore


def run_bot() -> None:
Expand Down
36 changes: 18 additions & 18 deletions cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,58 +18,58 @@ def __init__(self, bot: ValorantBot) -> None:

@commands.command()
@commands.is_owner()
async def sync(self, ctx: commands.Context, sync_type: Literal['guild', 'global']) -> None:
async def sync(self, ctx: commands.Context[ValorantBot], sync_type: Literal['guild', 'global']) -> None:
"""Sync the application commands"""

async with ctx.typing():
if sync_type == 'guild':
self.bot.tree.copy_global_to(guild=ctx.guild)
self.bot.tree.copy_global_to(guild=ctx.guild) # type: ignore
await self.bot.tree.sync(guild=ctx.guild)
await ctx.reply(f"Synced guild !")
await ctx.reply('Synced guild !')
return

await self.bot.tree.sync()
await ctx.reply(f"Synced global !")
await ctx.reply('Synced global !')

@commands.command()
@commands.is_owner()
async def unsync(self, ctx: commands.Context, unsync_type: Literal['guild', 'global']) -> None:
async def unsync(self, ctx: commands.Context[ValorantBot], unsync_type: Literal['guild', 'global']) -> None:
"""Unsync the application commands"""

async with ctx.typing():
if unsync_type == 'guild':
self.bot.tree.clear_commands(guild=ctx.guild)
await self.bot.tree.sync(guild=ctx.guild)
await ctx.reply(f"Un-Synced guild !")
await ctx.reply('Un-Synced guild !')
return

self.bot.tree.clear_commands()
self.bot.tree.clear_commands() # type: ignore
await self.bot.tree.sync()
await ctx.reply(f"Un-Synced global !")
await ctx.reply('Un-Synced global !')

@app_commands.command(description='Shows basic information about the bot.')
async def about(self, interaction: Interaction) -> None:
"""Shows basic information about the bot."""

owner_url = f'https://discord.com/users/240059262297047041'
owner_url = 'https://discord.com/users/240059262297047041'
github_project = 'https://github.com/staciax/Valorant-DiscordBot'
support_url = 'https://discord.gg/FJSXPqQZgz'

embed = discord.Embed(color=0xFFFFFF)
embed.set_author(name='VALORANT BOT PROJECT', url=github_project)
embed.set_thumbnail(url='https://i.imgur.com/ZtuNW0Z.png')
embed.add_field(name='DEV:', value=f"[ꜱᴛᴀᴄɪᴀ.#7475]({owner_url})", inline=False)
embed.add_field(name='DEV:', value=f'[ꜱᴛᴀᴄɪᴀ.#7475]({owner_url})', inline=False)
embed.add_field(
name='ᴄᴏɴᴛʀɪʙᴜᴛᴏʀꜱ:',
value=f"[kiznick](https://github.com/kiznick)\n"
"[KANATAISGOD](https://github.com/KANATAISGOD)\n"
value='[kiznick](https://github.com/kiznick)\n'
'[KANATAISGOD](https://github.com/KANATAISGOD)\n'
"[TMADZ2007](https://github.com/KANATAISGOD')\n"
"[sevzin](https://github.com/sevzin)\n"
"[MIIGØ](https://github.com/miigo-dev)\n"
"[Connor](https://github.com/ConnorDoesDev)\n"
"[KohanaSann](https://github.com/KohanaSann)\n"
"[RyugaXhypeR](https://github.com/RyugaXhypeR)\n"
"[Austin Hornhead](https://github.com/marchingon12)\n",
'[sevzin](https://github.com/sevzin)\n'
'[MIIGØ](https://github.com/miigo-dev)\n'
'[Connor](https://github.com/ConnorDoesDev)\n'
'[KohanaSann](https://github.com/KohanaSann)\n'
'[RyugaXhypeR](https://github.com/RyugaXhypeR)\n'
'[Austin Hornhead](https://github.com/marchingon12)\n',
inline=False,
)
view = ui.View()
Expand Down
54 changes: 27 additions & 27 deletions cogs/errors.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import traceback
from typing import TYPE_CHECKING, Union
from typing import TYPE_CHECKING

import discord
from discord import Interaction
Expand Down Expand Up @@ -44,56 +44,56 @@ async def on_app_command_error(self, interaction: Interaction, error: AppCommand
if self.bot.debug is True:
traceback.print_exception(type(error), error, error.__traceback__)

error_message = 'An unknown error occurred, sorry'
# if isinstance(error, CommandInvokeError):
# error = error.original
if isinstance(error, NotOwner):
error = "You are not the owner of this bot."
error_message = 'You are not the owner of this bot.'
elif isinstance(error, BadArgument):
error = "Bad argument."
elif isinstance(error, (ValorantBotError, ResponseError, HandshakeError, DatabaseError, AuthenticationError)):
error = error
error_message = 'Bad argument.'
elif isinstance(
error, (ValorantBotError | ResponseError | HandshakeError | DatabaseError | AuthenticationError)
):
error_message = error
elif isinstance(error, ResponseError):
error = "Empty response from Riot server."
error_message = 'Empty response from Riot server.'
elif isinstance(error, HandshakeError):
error = "Could not connect to Riot server."
elif isinstance(error, CommandOnCooldown):
error = error
elif isinstance(error, Union[AppCommandNotFound, MissingPermissions, BotMissingPermissions]):
error_message = 'Could not connect to Riot server.'
elif isinstance(error, (CommandOnCooldown | AppCommandNotFound | MissingPermissions | BotMissingPermissions)):
error = error
else:
error = f"An unknown error occurred, sorry"
traceback.print_exception(type(error), error)
# else:
# traceback.print_exception(type(error), error)

embed = discord.Embed(description=f'{str(error)[:2000]}', color=0xFE676E)
embed = discord.Embed(description=f'{str(error_message)[:2000]}', color=0xFE676E)
if interaction.response.is_done():
return await interaction.followup.send(embed=embed, ephemeral=True)
await interaction.response.send_message(embed=embed, ephemeral=True)

@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error: Exception) -> None:
async def on_command_error(self, ctx: commands.Context[ValorantBot], error: Exception) -> None:
embed = discord.Embed(color=0xFE676E)

if isinstance(error, CommandNotFound):
return
elif isinstance(error, CheckFailure):
cm_error = "Only owners can run this command!"
cm_error = 'Only owners can run this command!'
elif isinstance(error, MissingRequiredArgument):
cm_error = f"You didn't pass a required argument!"
if ctx.command.name in ['sync', 'unsync']:
cm_error = f"You need to specify a sync type: `guild` or `global`"
elif hasattr(error, "original"):
if isinstance(error.original, discord.Forbidden):
cm_error = f"Bot don't have permission to run this command."
if ctx.command.name in ['sync', 'unsync']:
cm_error = f"Bot don't have permission `applications.commands` to sync."
cm_error = "You didn't pass a required argument!"
if ctx.command and ctx.command.name in ['sync', 'unsync']:
cm_error = 'You need to specify a sync type: `guild` or `global`'
elif hasattr(error, 'original'):
if isinstance(error.original, discord.Forbidden): # type: ignore
cm_error = "Bot don't have permission to run this command."
if ctx.command and ctx.command.name in ['sync', 'unsync']:
cm_error = "Bot don't have permission `applications.commands` to sync."
embed.set_image(url=app_cmd_scope)
elif isinstance(error.original, discord.HTTPException):
cm_error = f"An error occurred while processing your request."
elif isinstance(error.original, discord.HTTPException): # type: ignore
cm_error = 'An error occurred while processing your request.'
elif isinstance(error, BadLiteralArgument):
cm_error = f"**Invalid literal:** {', '.join(error.literals)}"
else:
traceback.print_exception(type(error), error, error.__traceback__)
cm_error = f"An unknown error occurred, sorry"
cm_error = 'An unknown error occurred, sorry'

embed.description = cm_error
await ctx.send(embed=embed, delete_after=30, ephemeral=True)
Expand Down
Loading
Loading