Skip to content

Commit

Permalink
Merge branch 'develop' into l10n_develop
Browse files Browse the repository at this point in the history
  • Loading branch information
ZRunner authored Nov 18, 2023
2 parents b241448 + a4327db commit 7b161e8
Show file tree
Hide file tree
Showing 28 changed files with 1,082 additions and 573 deletions.
2 changes: 1 addition & 1 deletion docs/roles-reactions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@ The second argument 'changeDescription' can be used when you don't want Axobot t

You can also use the third argument, a list of emojis, if you want your embed to contain only specific roles/emojis. Thus you can create different roles-reactions embeds with the same system.

.. note:: Note that there are two criteria for the bot to recognize the embed as its own: it must be sent by itself, and the footer text must be the same as in the official embeds. This means that you can use the `embed` command to send a custom embed, it will still work.
.. note:: Note that there are two criteria for the bot to recognize the embed as its own: it must be sent by itself, and the footer text must be the same as in the official embeds (i.e. :code:`Axobot roles reactions`). This means that you can use the `embed` command to send a custom embed, it will still work.
52 changes: 52 additions & 0 deletions events-list.json
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,57 @@
],
"probability": 0.05
}
},
"christmas-2023": {
"begin": "2023-11-01",
"end": "2023-12-31",
"type": "christmas",
"icon": "https://zrunner.me/cdn/halloween_2023.png",
"color": 4886759,
"objectives": [
{
"points": 300,
"reward_type": "role",
"role_id": 1159531747877330994
},
{
"points": 600,
"reward_type": "rankcard",
"rank_card": "christmas23",
"min_date": "2023-10-25"
}
],
"emojis": {
"reactions_list": [
"",
"",
"🎅",
"🎄",
"🎁"
],
"triggers": [
"christmas",
"xmas",
"present",
"noël",
"santa",
"gift",
"cadeau",
"snow",
"neige",
"ice",
"glace",
"ho ho ho",
"reinder",
"sleight",
"traîneau",
"candy cane",
"sucre d'orge",
"elf ",
"lutin",
"cookie"
],
"probability": 0.91
}
}
}
500 changes: 103 additions & 397 deletions fcts/bot_events.py

Large diffs are not rendered by default.

44 changes: 30 additions & 14 deletions fcts/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,12 @@ async def roll(self, ctx: MyContext, *, options: str):
..Example roll Play Minecraft, play Star Citizens, do homeworks
..Doc fun.html#roll"""
liste = list(set([x for x in [x.strip() for x in options.split(',')] if len(x) > 0]))
if len(liste) == 0:
possibilities = list({x for x in [x.strip() for x in options.split(',')] if len(x) > 0})
if len(possibilities) == 0:
return await ctx.send(await self.bot._(ctx.channel,"fun.no-roll"))
elif len(liste) == 1:
elif len(possibilities) == 1:
return await ctx.send(await self.bot._(ctx.channel,"fun.not-enough-roll"))
choosen = random.choice(liste)
choosen = random.choice(possibilities)
await ctx.send(choosen)

@commands.command(name="cookie", aliases=['cookies', 'crustulum'], hidden=True)
Expand Down Expand Up @@ -261,14 +261,14 @@ async def blame(self, ctx: MyContext, name: str):
if await self.is_on_guild(ctx.author, 523525264517496834): # Benny Support
await ctx.send(file=await self.utilities.find_img(f'blame-{name}.png'))
elif name in ['help','list']:
liste = l1
available_names = l1
if await self.is_on_guild(ctx.author, 391968999098810388): # fr-minecraft
liste += l2
available_names += l2
if await self.is_on_guild(ctx.author, SUPPORT_GUILD_ID.id): # Axobot server
liste += l3
available_names += l3
if await self.is_on_guild(ctx.author, 523525264517496834): # Benny Support
liste += l4
txt = "- "+"\n- ".join(sorted(liste))
available_names += l4
txt = "- "+"\n- ".join(sorted(available_names))
title = await self.bot._(ctx.channel, "fun.blame-0", user=ctx.author)
if ctx.can_send_embed:
emb = discord.Embed(title=title, description=txt, color=self.bot.get_cog("Help").help_color)
Expand All @@ -291,17 +291,18 @@ async def kill(self, ctx: MyContext, *, name: typing.Optional[str]=None):
victime = name
ex = victime.replace(" ", "_")
author = ctx.author.mention
liste = await self.bot._(ctx.channel, "fun.kills-list")
msg = random.choice(liste)
possibilities = await self.bot._(ctx.channel, "fun.kills-list")
msg = random.choice(possibilities)
tries = 0
while '{attacker}' in msg and name is None and tries<50:
msg = random.choice(liste)
msg = random.choice(possibilities)
tries += 1
await ctx.send(msg.format(attacker=author, victim=victime, ex=ex))

@commands.command(name="arapproved",aliases=['arapprouved'],hidden=True)
@commands.command(name="arapproved",aliases=['arapprouved'], hidden=True)
@commands.check(lambda ctx: ctx.author.id in [375598088850505728,279568324260528128])
async def arapproved(self, ctx: MyContext):
"If you don't know why this exists, it's probably not for you"
await ctx.send(file=await self.utilities.find_img("arapproved.png"))

@commands.command(name='party',hidden=True)
Expand All @@ -324,6 +325,7 @@ async def party(self, ctx: MyContext):
await ctx.send(file=await self.utilities.find_img('cameleon.gif'))

@commands.command(name="cat", hidden=True)
@commands.cooldown(5, 7, commands.BucketType.user)
@commands.check(is_fun_enabled)
async def cat_gif(self, ctx: MyContext):
"""Wow... So cuuuute !
Expand All @@ -334,7 +336,21 @@ async def cat_gif(self, ctx: MyContext):
'https://25.media.tumblr.com/7774fd7794d99b5998318ebd5438ba21/tumblr_n2r7h35U211rudcwro1_400.gif',
'https://tenor.com/view/seriously-seriously-cat-cat-really-cat-really-look-cat-look-gif-22182662',
'http://coquelico.c.o.pic.centerblog.net/chat-peur.gif',
'https://tenor.com/view/nope-bye-cat-leave-done-gif-12387359'
'https://tenor.com/view/nope-bye-cat-leave-done-gif-12387359',
'https://tenor.com/view/cute-cat-kitten-kitty-pussy-cat-gif-16577050',
'https://tenor.com/view/cat-box-gif-18395469',
'https://tenor.com/view/pile-cats-cute-silly-meowtain-gif-5791255',
'https://tenor.com/view/cat-fight-cats-cat-love-pet-lover-pelea-gif-13002823369159732311',
'https://tenor.com/view/cat-disapear-cat-snow-cat-jump-fail-cat-fun-jump-cats-gif-17569677',
'https://tenor.com/view/black-cat-tiny-cat-smol-kitten-airplane-ears-cutie-pie-gif-23391953',
'https://tenor.com/view/cat-cats-catsoftheinternet-biting-tale-cat-bite-gif-23554005',
'https://tenor.com/view/on-my-way-cat-run-cat-on-my-way-cat-cat-on-my-way-gif-26471384',
'https://tenor.com/view/cat-cat-activity-goober-goober-cat-silly-cat-gif-186256394908832033',
'https://tenor.com/view/cat-stacked-kittens-kitty-pussy-cats-gif-16220908',
'https://tenor.com/view/cute-cat-cats-cats-of-the-internet-cattitude-gif-17600906',
'https://tenor.com/view/cat-scared-hide-terrified-frightened-gif-17023981',
'https://tenor.com/view/cat-running-away-escape-getaway-bye-gif-16631286',
'https://tenor.com/view/bye-cat-box-tight-face-bored-cat-gif-7986182'
]))

@commands.command(name="happy-birthday", hidden=True, aliases=['birthday', 'hb'])
Expand Down
14 changes: 7 additions & 7 deletions fcts/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,15 +947,15 @@ async def snowflake_info(self, interaction: discord.Interaction, snowflake: args
async def find_user(self, interaction: discord.Interaction, user: discord.User):
"Find any user visible by the bot"
# Servers list
servers_in = list()
servers_in: list[str] = []
owned, membered = 0, 0
if hasattr(user, "mutual_guilds"):
for s in user.mutual_guilds:
if s.owner==user:
servers_in.append(":crown: "+s.name)
servers_in.append(f":crown: {s.name} ({s.id})")
owned += 1
else:
servers_in.append("- "+s.name)
servers_in.append(f"- {s.name} ({s.id})")
membered += 1
if len("\n".join(servers_in)) > 1020:
servers_in = [f"{owned} owned servers, member of {membered} others"]
Expand All @@ -978,7 +978,7 @@ async def find_user(self, interaction: discord.Interaction, user: discord.User):
disp_lang = list()
if hasattr(user, "mutual_guilds"):
for lang in await self.bot.get_cog('Utilities').get_languages(user):
disp_lang.append('{} ({}%)'.format(lang[0], round(lang[1]*100)))
disp_lang.append(f"{lang[0]} ({lang[1]*100:.0f}%)")
if len(disp_lang) == 0:
disp_lang = ["Unknown"]
# User name
Expand All @@ -990,9 +990,9 @@ async def find_user(self, interaction: discord.Interaction, user: discord.User):
user_name = user.name
# XP sus
xp_sus = "Unknown"
if Xp := self.bot.get_cog("Xp"):
if Xp.sus is not None:
xp_sus = str(user.id in Xp.sus)
if xp_cog := self.bot.get_cog("Xp"):
if xp_cog.sus is not None:
xp_sus = str(user.id in xp_cog.sus)
# ----
if interaction.guild is None:
color = None
Expand Down
46 changes: 28 additions & 18 deletions fcts/roles_react.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import importlib
import re
from typing import Any, Optional, Tuple, Union
from typing import Any, Tuple, Union

import discord
from discord.ext import commands
Expand All @@ -14,20 +14,23 @@


class RolesReact(commands.Cog):
"Allow members to get new roles by clicking on reactions"

def __init__(self, bot: Axobot):
self.bot = bot
self.file = 'roles_react'
self.table = 'roles_react_beta' if bot.beta else 'roles_react'
self.guilds_which_have_roles = set()
self.cache_initialized = False
self.embed_color = 12118406
self.footer_txt = 'ZBot roles reactions'
self.footer_texts = ("Axobot roles reactions", "ZBot roles reactions")

@commands.Cog.listener()
async def on_ready(self):
self.table = 'roles_react_beta' if self.bot.beta else 'roles_react'

async def prepare_react(self, payload: discord.RawReactionActionEvent) -> Tuple[discord.Message, discord.Role]:
"Handle new added/removed reactions and check if they are roles reactions"
if payload.guild_id is None or payload.user_id == self.bot.user.id:
return None, None
if not self.cache_initialized:
Expand All @@ -42,11 +45,16 @@ async def prepare_react(self, payload: discord.RawReactionActionEvent) -> Tuple[
except discord.NotFound: # we don't care about those
return None, None
except Exception as err:
self.bot.log.warning(f"Could not fetch roles-reactions message {payload.message_id} in guild {payload.guild_id}: {err}")
self.bot.log.warning(
f"Could not fetch roles-reactions message {payload.message_id} in guild {payload.guild_id}: {err}"
)
return None, None
if len(msg.embeds) == 0 or msg.embeds[0].footer.text != self.footer_txt:
if len(msg.embeds) == 0 or msg.embeds[0].footer.text not in self.footer_texts:
return None, None
temp = await self.rr_list_role(payload.guild_id, payload.emoji.id if payload.emoji.is_custom_emoji() else payload.emoji.name)
temp = await self.rr_list_role(
payload.guild_id,
payload.emoji.id if payload.emoji.is_custom_emoji() else payload.emoji.name
)
if len(temp) == 0:
return None, None
role = self.bot.get_guild(payload.guild_id).get_role(temp[0]["role"])
Expand Down Expand Up @@ -79,7 +87,7 @@ async def on_raw_reaction_event(self, payload: discord.RawReactionActionEvent, i

async def rr_get_guilds(self) -> set:
"""Get the list of guilds which have roles reactions"""
query = "SELECT `guild` FROM `{}`;".format(self.table)
query = f"SELECT `guild` FROM `{self.table}`;"
async with self.bot.db_query(query) as query_results:
self.guilds_which_have_roles = {x['guild'] for x in query_results}
self.cache_initialized = True
Expand All @@ -89,30 +97,30 @@ async def rr_add_role(self, guild: int, role: int, emoji: str, desc: str):
"""Add a role reaction in the database"""
if isinstance(emoji, discord.Emoji):
emoji = emoji.id
query = ("INSERT INTO `{}` (`guild`,`role`,`emoji`,`description`) VALUES (%(g)s,%(r)s,%(e)s,%(d)s);".format(self.table))
query = f"INSERT INTO `{self.table}` (`guild`,`role`,`emoji`,`description`) VALUES (%(g)s,%(r)s,%(e)s,%(d)s);"
async with self.bot.db_query(query, {'g': guild, 'r': role, 'e': emoji, 'd': desc}):
pass
return True

async def rr_list_role(self, guild: int, emoji: str = None):
async def rr_list_role(self, guild_id: int, emoji: str = None):
"""List role reaction in the database"""
if isinstance(emoji, discord.Emoji):
emoji = emoji.id
if emoji is None:
query = "SELECT * FROM `{}` WHERE guild={} ORDER BY added_at;".format(self.table, guild)
query = f"SELECT * FROM `{self.table}` WHERE guild=%(g)s ORDER BY added_at;"
else:
query = "SELECT * FROM `{}` WHERE guild={} AND emoji='{}' ORDER BY added_at;".format(self.table, guild, emoji)
query = f"SELECT * FROM `{self.table}` WHERE guild=%(g)s AND emoji=%(e)s ORDER BY added_at;"
liste: list[dict[str, Any]] = []
async with self.bot.db_query(query) as query_results:
async with self.bot.db_query(query, {"g": guild_id, "e": emoji}) as query_results:
for row in query_results:
if emoji is None or row['emoji'] == str(emoji):
liste.append(row)
return liste

async def rr_remove_role(self, rr_id: int):
"""Remove a role reaction from the database"""
query = ("DELETE FROM `{}` WHERE `ID`={};".format(self.table, rr_id))
async with self.bot.db_query(query):
query = f"DELETE FROM `{self.table}` WHERE `ID`=%s;"
async with self.bot.db_query(query, (rr_id,)):
pass
return True

Expand Down Expand Up @@ -246,7 +254,7 @@ async def rr_get(self, ctx: MyContext):
des, emojis = await self.create_list_embed(roles_list, ctx.guild)
title = await self.bot._(ctx.guild.id, "roles_react.rr-embed")
emb = discord.Embed(title=title, description=des, color=self.embed_color, timestamp=ctx.message.created_at)
emb.set_footer(text=self.footer_txt)
emb.set_footer(text=self.footer_texts[0])
msg = await ctx.send(embed=emb)
for emoji in emojis:
try:
Expand Down Expand Up @@ -319,11 +327,13 @@ async def give_remove_role(self, user: discord.Member, role: discord.Role, guild
self.bot.dispatch("error", err)
else:
if not ignore_success:
await channel.send(await self.bot._(guild.id, "roles_react.role-given" if give else "roles_react.role-lost", r=role.name))
await channel.send(
await self.bot._(guild.id, "roles_react.role-given" if give else "roles_react.role-lost", r=role.name)
)

@rr_main.command(name='update')
@commands.check(checks.database_connected)
async def rr_update(self, ctx: MyContext, embed: discord.Message, change_description: Optional[bool] = True,
async def rr_update(self, ctx: MyContext, embed: discord.Message, change_description: bool = True,
emojis: commands.Greedy[Union[discord.Emoji, args.UnicodeEmoji]] = None):
"""Update an Axobot message to refresh roles/reactions
If you don't want to update the embed content (for example if it's a custom embed) then you can use 'False' as a second argument, and I will only check the reactions
Expand All @@ -336,10 +346,10 @@ async def rr_update(self, ctx: MyContext, embed: discord.Message, change_descrip
..Doc roles-reactions.html#update-your-embed"""
if embed.author != ctx.guild.me:
return await ctx.send(await self.bot._(ctx.guild, "roles_react.not-zbot-msg"))
if len(embed.embeds) != 1 or embed.embeds[0].footer.text != self.footer_txt:
if len(embed.embeds) != 1 or embed.embeds[0].footer.text not in self.footer_texts:
return await ctx.send(await self.bot._(ctx.guild, "roles_react.not-zbot-embed"))
if not embed.channel.permissions_for(embed.guild.me).add_reactions:
return await ctx.send(await self.bot._(ctx.guild, 'fun', "cant-react"))
return await ctx.send(await self.bot._(ctx.guild, "poll.cant-react"))
emb = embed.embeds[0]
try:
full_list: dict[str, dict[str, Any]] = {x['emoji']: x for x in await self.rr_list_role(ctx.guild.id)}
Expand Down
Loading

0 comments on commit 7b161e8

Please sign in to comment.