Skip to content
This repository has been archived by the owner on Jan 26, 2024. It is now read-only.

Commit

Permalink
Merge pull request #21 from ilyash0/dev
Browse files Browse the repository at this point in the history
v0.4.2
  • Loading branch information
ilyash0 authored Dec 30, 2023
2 parents 4afef45 + 9ac198b commit 5b897e3
Show file tree
Hide file tree
Showing 10 changed files with 68 additions and 35 deletions.
28 changes: 20 additions & 8 deletions bot/core/puffleBot.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import os
import traceback
from datetime import datetime, timedelta

import disnake
from disnake import Webhook, Game, AppCommandInter
from disnake.ext.commands import InteractionBot, CommandError
from disnake.ext.commands import InteractionBot, CommandError, CommandOnCooldown
from loguru import logger
import bot.locale
import bot.handlers.cogs
Expand Down Expand Up @@ -46,7 +47,12 @@ async def on_ready(self):
logger.info(f"Bot {self.user} ready")

async def on_slash_command(self, inter: AppCommandInter):
logger.debug(f"{inter.author} use slash command /{inter.data.name} in #{inter.channel}")
if not len(inter.data.options):
logger.debug(
f"{inter.author} use slash command /{inter.data.name} in #{inter.channel} in guild {inter.guild}")
else:
logger.debug(
f"{inter.author} use slash command /{inter.data.name} in #{inter.channel} in guild {inter.guild} with options: {inter.data.options} ")
if self.defer and inter.data.name not in non_deferred_commands:
try:
await inter.response.defer()
Expand Down Expand Up @@ -97,21 +103,27 @@ async def on_connect(self):
# except asyncpg.exceptions.UndefinedTableError:
# pass

async def on_slash_command_error(self, inter: AppCommandInter, exception: CommandError):
async def on_slash_command_error(self, inter: AppCommandInter, exception: CommandError or CommandOnCooldown):
try:
if (exception.args[0] ==
"Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions"):
logger.error(f"403 Forbidden: Missing Permissions")
if isinstance(exception, CommandOnCooldown):
end_time = f"<t:{int((datetime.now() + timedelta(seconds=exception.retry_after)).timestamp())}:R>"
await inter.send(
f"{self.i18n.get('COMMAND_COOLDOWN_RESPONSE')[str(inter.avail_lang)].replace('%time%',end_time)}",
ephemeral=True)
logger.error(f"User error: {exception.args[0]}")
elif (exception.args[0] ==
"Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions"):
await inter.send(f"{self.i18n.get('BOT_DOESNT_HAVE_PERMISSION')[str(inter.avail_lang)]}",
ephemeral=True)
logger.error(f"403 Forbidden: Missing Permissions")
else:
logger.error(f"User error: {exception.args[0]}")
await inter.send(f"{self.i18n.get(exception.args[0])[str(inter.avail_lang)]}", ephemeral=True)
logger.error(f"User error: {exception.args[0]}")

except (KeyError, TypeError, AttributeError):
await inter.send(f"Unknown error", ephemeral=True)
logger.error(exception)
traceback.print_exception(type(exception), exception, exception.__traceback__)
await inter.send(f"Unknown error", ephemeral=True)

async def on_error(self, event_method: str, *args, **kwargs):
logger.error(f"Ignoring exception in {event_method}")
Expand Down
30 changes: 20 additions & 10 deletions bot/handlers/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,18 +325,28 @@ def __init__(self, original_inter: AppCommandInter, message: Message, coins: int
self.message = message
self.coins = coins
self.giver_penguin: Penguin = giver_penguin
self.collected: bool = False
self.processed: bool = False

@disnake.ui.button(label="GIFT", style=disnake.ButtonStyle.blurple, custom_id="gift", emoji="🎁")
async def gift(self, button, inter: MessageInteraction):
if self.processed:
raise Exception("TOO_LATE")
self.processed = True

await inter.response.defer()
p = await get_my_penguin_from_user_id(inter.user.id)
if p.moderator or p.id == self.giver_penguin.id:
await inter.send(inter.bot.i18n.get("NOT_FOR_YOU")[str(inter.locale)], ephemeral=True)
return

await transfer_coins(self.giver_penguin, p, self.coins)
await inter.send(inter.bot.i18n.get("GIFT_RESPONSE")[str(inter.locale)].
replace("%coins%", str(self.coins)).replace("%nickname%", p.safe_name()))
await notify_gift_coins(inter.user, p, self.coins)
button.disabled = True
await self.message.edit(view=self)
try:
p = await get_my_penguin_from_user_id(inter.user.id)
if p.moderator or p.id == self.giver_penguin.id:
raise Exception("NOT_FOR_YOU")

await transfer_coins(self.giver_penguin, p, self.coins)
await inter.send(inter.bot.i18n.get("GIFT_RESPONSE")[str(inter.locale)].
replace("%coins%", str(self.coins)).replace("%nickname%", p.safe_name()))
self.collected = True
await notify_gift_coins(inter.user, p, self.coins)
finally:
self.processed = self.collected
button.disabled = self.collected
await self.message.edit(view=self)
11 changes: 7 additions & 4 deletions bot/handlers/cogs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
from random import randrange

from bs4 import BeautifulSoup
from disnake import AppCommandInter, Localized
from disnake import AppCommandInter, Localized, AllowedMentions
from loguru import logger
import disnake
from disnake.ext.commands import Cog, Param, slash_command, CommandError
from disnake.ext.commands import Cog, Param, slash_command, CommandError, cooldown, BucketType
from requests import Session

from bot.data import db_pb
Expand Down Expand Up @@ -226,6 +226,7 @@ async def top(self, inter: AppCommandInter,
await inter.send(embed=embed, view=view)

@slash_command()
@cooldown(1, 60, BucketType.user)
async def gift(self, inter: AppCommandInter, channel: disnake.TextChannel, coins: int, message: str = None):
"""
Gift coins to users in a specific channel {{GIFT}}
Expand Down Expand Up @@ -253,10 +254,12 @@ async def gift(self, inter: AppCommandInter, channel: disnake.TextChannel, coins
if p.coins < coins:
raise CommandError("NOT_ENOUGH_COINS")

message_object = await channel.send(f"{message} {self.bot.i18n.get('WAIT_A_FEW_SECONDS')[lang]}")
message_object = await channel.send(f"{message} {self.bot.i18n.get('WAIT_A_FEW_SECONDS')[lang]}",
allowed_mentions=AllowedMentions(roles=False, users=False, everyone=False))
await inter.send(self.bot.i18n.get("SUCCESS")[lang], ephemeral=True)
await sleep(randrange(3, 15))
await message_object.edit(message, view=Gift(inter, message_object, coins, p))
await message_object.edit(message, view=Gift(inter, message_object, coins, p),
allowed_mentions=AllowedMentions(roles=False, users=False, everyone=False))


def setup(bot):
Expand Down
3 changes: 2 additions & 1 deletion bot/handlers/cogs/fundraising.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import disnake
from disnake import AppCommandInter, Embed
from disnake.ext.commands import Cog, slash_command
from disnake.ext.commands import Cog, slash_command, cooldown, BucketType
from loguru import logger

from bot.data.pufflebot.fundraising import Fundraising
Expand All @@ -20,6 +20,7 @@ async def fundraising(self, inter: AppCommandInter):
...

@fundraising.sub_command(name="open")
@cooldown(1, 300, BucketType.user)
async def fundraising_open(self, inter: AppCommandInter, title: str, coins: int = None):
"""
Start a fundraising {{FR_OPEN}}
Expand Down
6 changes: 4 additions & 2 deletions bot/locale/en_GB.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"RULES_DESCRIPTION": "Send rules embed",
"ABOUT_DESCRIPTION": "Send about embed",
"STATISTIC_DESCRIPTION": "Shows game statistics",
"GIFT_DESCRIPTION": "Gift coins to users in a specific channel ",
"GIFT_DESCRIPTION": "Gift coins to users in a specific channel",

"USER_NAME": "user",
"COINS_NAME": "coins",
Expand Down Expand Up @@ -149,5 +149,7 @@
"PLAYER_RETENTION": "Player retention",
"ECONOMIC_DATA": "Economic data",
"MICROTRANSACTION_REVENUE": "Total revenue from microtransactions",
"GIFT_RESPONSE": "A gift of %coins% coins is claimed by %nickname%"
"GIFT_RESPONSE": "A gift of %coins% coins is claimed by %nickname%",
"COMMAND_COOLDOWN_RESPONSE": "This command is on cooldown. Try again in %time%",
"TOO_LATE": "It's too late"
}
6 changes: 4 additions & 2 deletions bot/locale/en_US.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"RULES_DESCRIPTION": "Send rules embed",
"ABOUT_DESCRIPTION": "Send about embed",
"STATISTIC_DESCRIPTION": "Shows game statistics",
"GIFT_DESCRIPTION": "Gift coins to users in a specific channel ",
"GIFT_DESCRIPTION": "Gift coins to users in a specific channel",

"USER_NAME": "user",
"COINS_NAME": "coins",
Expand Down Expand Up @@ -149,5 +149,7 @@
"PLAYER_RETENTION": "Player retention",
"ECONOMIC_DATA": "Economic data",
"MICROTRANSACTION_REVENUE": "Total revenue from microtransactions",
"GIFT_RESPONSE": "A gift of %coins% coins is claimed by %nickname%"
"GIFT_RESPONSE": "A gift of %coins% coins is claimed by %nickname%",
"COMMAND_COOLDOWN_RESPONSE": "This command is on cooldown. Try again in %time%",
"TOO_LATE": "It's too late"
}
5 changes: 3 additions & 2 deletions bot/locale/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@
"TOP-UP": "Uzupełnienie konta",
"END_MEMBERSHIP": "Koniec subskrypcji",
"OTHER_AMOUNT": "Inna suma",
"All": "Wszystko",
"CLOSED": "Zamnknięty",
"MESSAGE": "Wiadomość",
"COMMAND": "Polecenie",
Expand Down Expand Up @@ -150,5 +149,7 @@
"PLAYER_RETENTION": "Zatrzymanie użytkowników",
"ECONOMIC_DATA": "Dane ekonomiczne",
"MICROTRANSACTION_REVENUE": "Całkowite przychody od mikrotranzakcji",
"GIFT_RESPONSE": "Prezent w postaci %coins% monet został odebrany przez %nickname%"
"GIFT_RESPONSE": "Prezent w postaci %coins% monet został odebrany przez %nickname%",
"COMMAND_COOLDOWN_RESPONSE": "To polecenie jest w trakcie odnawiania. Spróbuj ponownie za %time%",
"TOO_LATE": "Jest już za późno"
}
5 changes: 3 additions & 2 deletions bot/locale/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@
"TOP-UP": "Пополнение баланса",
"END_MEMBERSHIP": "Окончание подписки",
"OTHER_AMOUNT": "Другая сумма",
"All": "Все",
"CLOSED": "Закрыт",
"MESSAGE": "Сообщение",
"COMMAND": "Команда",
Expand Down Expand Up @@ -150,5 +149,7 @@
"PLAYER_RETENTION": "Удержание пользователей",
"ECONOMIC_DATA": "Экономические данные",
"MICROTRANSACTION_REVENUE": "Общая выручка от микротранзакций",
"GIFT_RESPONSE": "Подарок в виде %coins% монет забирает %nickname%"
"GIFT_RESPONSE": "Подарок в виде %coins% монет забирает %nickname%",
"COMMAND_COOLDOWN_RESPONSE": "Эта команда находится в режиме ожидания. Повторите попытку через %time%",
"TOO_LATE": "Слишком поздно"
}
5 changes: 3 additions & 2 deletions bot/locale/uk.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@
"TOP-UP": "Поповнення балансу",
"END_MEMBERSHIP": "Закінчення підписки",
"OTHER_AMOUNT": "Інша сума",
"All": "Все",
"CLOSED": "Закритий",
"MESSAGE": "Повідомлення",
"COMMAND": "Команда",
Expand Down Expand Up @@ -150,5 +149,7 @@
"PLAYER_RETENTION": "Утримання користувачів",
"ECONOMIC_DATA": "Экономічні дані",
"MICROTRANSACTION_REVENUE": "Загальна виручка від мікротранзакцій",
"GIFT_RESPONSE": "Подарунок у вигляді %coins% монет забирає %nickname%"
"GIFT_RESPONSE": "Подарунок у вигляді %coins% монет забирає %nickname%",
"COMMAND_COOLDOWN_RESPONSE": "Ця команда перебуває у стані охолодження. Спробуйте ще раз через %time%",
"TOO_LATE": "Занадто пізно"
}
4 changes: 2 additions & 2 deletions bot/misc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async def get_my_penguin_from_user_id(user_id: int) -> Penguin:
If the penguin is not found, this function raises a KeyError with the message "MY_PENGUIN_NOT_FOUND."
"""
user = await User.get(user_id)
if user is None:
if user is None or user.penguin_id is None:
raise KeyError("MY_PENGUIN_NOT_FOUND")
return await get_penguin_from_penguin_id(user.penguin_id)

Expand All @@ -52,7 +52,7 @@ async def get_penguin_or_none_from_user_id(user_id: int) -> Penguin or None:
The penguin object, or `None` if the user is not found.
"""
user = await User.get(user_id)
if user is None:
if user is None or user.penguin_id is None:
return None
return await get_penguin_from_penguin_id(user.penguin_id)

Expand Down

0 comments on commit 5b897e3

Please # to comment.