async def raceday_loop(self): year = datetime.datetime.now().year data = await self.get(f"/{year}.json") if data.get("failed"): return circuits = data["MRData"]["RaceTable"]["Races"] if not circuits: return for circuit in circuits: time = datetime.datetime.fromisoformat( circuit["date"] + "T" + circuit["time"].replace("Z", "") ).replace(tzinfo=datetime.timezone.utc) if time.date() == datetime.datetime.now().date(): data = await self.config.all_guilds() for guild_id in data: try: guild = self.bot.get_guild(int(guild_id)) if guild is None: log.debug("Guild %d not found", guild) continue channel = guild.get_channel(data[guild_id]["channel"]) if channel is None: log.debug("Channel %d not found", channel) continue msg = "" if data[guild_id]["role"] is not None: role = guild.get_role(data[guild_id]["role"]) if role is not None: msg += f"{role.mention}, " msg += f"**Race Day**!\n**{circuit['raceName']}** (Round {circuit['round']}) at **{circuit['Circuit']['circuitName']}** is starting today!\n**Race Start**: <t:{int(time.timestamp())}:F>" await channel.send(msg, allowed_mentions=AllowedMentions.all()) except Exception as e: log.exception(e)
async def unregister_role(self, ctx, reaction, role: discord.Role, message: discord.Message = None): data = json_open(reactrole_path) guild_id = ctx.guild.id guild_dict = data if not message: message = self.temp_message if not message: await ctx.send( "Please specify a message by adding message URL, message ID, or by setting a temporary message with `set_message` command." ) return if reaction.startswith('<'): reaction_name = re.findall(r":([^:]*):", reaction) reaction_name = reaction_name[0] else: reaction_name = reaction channel_dict = guild_dict[str(guild_id)] message_dict = channel_dict[str(message.channel.id)] react_role_dict = message_dict[str(message.id)] allowed_mentions = AllowedMentions(roles=False) del react_role_dict[reaction_name] message_dict[str(message.id)] = react_role_dict channel_dict[str(message.channel.id)] = message_dict guild_dict[str(guild_id)] = channel_dict data = guild_dict json_write(reactrole_path, data) await ctx.send( f"Removed {reaction} and {role} connection in the database", allowed_mentions=allowed_mentions)
async def _start(self): """Play the game""" # Sort out the players await self.pick_players() # Setup the categories and channels await self.setup_channels() # Now choose the godfather await self.choose_godfather() # Mafia channel must be locked await self.lock_mafia_channel() while True: if await self._cycle(): break # The game is done, allow dead players to chat again for player in self.players: if player.dead: await self.chat.set_permissions(player.member, read_messages=True) # Send winners winners = self.get_winners() msg = "Winners are:\n{}".format( "\n".join(f"{winner.member.name} ({winner})" for winner in winners) ) await self.chat.send(msg) # Send a message with everyone's roles msg = "\n".join( f"{player.member.mention} ({player})" for player in self.players ) await self.ctx.send(msg, allowed_mentions=AllowedMentions(users=False)) await asyncio.sleep(60) await self.cleanup_channels()
async def reroll(self, ctx: commands.Context, nwinners: int = None) -> None: """Rerolls the winners""" async with ctx.typing(): latest_giveaway = await self.get_latest_giveaway( ctx, force=True, only_previous=True) if latest_giveaway: try: winners = await self.roll_winner(ctx, latest_giveaway, nwinners) except ValueError: await ctx.send('Not enough participants.') else: fmt_winners = '\n'.join({i.mention for i in winners}) description = '\n'.join( latest_giveaway.embeds[0].description.split( '\n')[1:-(len(winners) + 1)]).strip() await ctx.send( f"Congratulations! Here are the **rerolled** winners for `{description}` <a:bahrooHi:402250652996337674>\n{fmt_winners}", allowed_mentions=AllowedMentions.all()) else: await ctx.send( 'No previous giveaway to reroll. To end a giveaway, use `giveaway stop`.' )
def __init__(self, *, tortoise_config, load_extensions=True, loadjsk=True): allowed_mentions = AllowedMentions(users=True, replied_user=True, roles=False, everyone=False) super().__init__( command_prefix=self.get_custom_prefix, intents=Intents.all(), allowed_mentions=allowed_mentions, description= "A bot by and for developers to integrate several tools into one place.", ) self.tortoise_config = tortoise_config self.db_connected = False self.prefix_cache = {} self.connect_db.start() if load_extensions: self.load_extensions(( "bot.core", "bot.cogs.admin", "bot.cogs.thank", "bot.cogs.stackexchange", "bot.cogs.github", "bot.cogs.help_command", "bot.cogs.code_exec", "bot.cogs.fun", "bot.cogs.rtfm", "bot.cogs.joke", "bot.cogs.utils", "bot.cogs.brainfeed", )) if loadjsk: self.load_extension("jishaku")
async def end_giveaway(self, giveaway: DBDict) -> None: latest_giveaway = await self.get_latest_giveaway(giveaway, force=True) try: winners = await self.roll_winner(giveaway, latest_giveaway) except (RuntimeError, ValueError): winners = None fmt_winners = None await giveaway.channel.send('Not enough participants.') else: fmt_winners = '\n'.join({i.mention for i in winners}) description = '\n'.join( giveaway.embeds[0].description.split('\n')[1:]) await giveaway.channel.send( f"Congratulations! Here are the winners for `{description}` <a:bahrooHi:402250652996337674>\n{fmt_winners}", allowed_mentions=AllowedMentions.all()) new_embed = giveaway.embeds[0] new_embed.title = 'Giveaway Ended' if winners: new_embed.description += f'\n\n**__Winners:__**\n{fmt_winners}' new_embed.color = INACTIVE_COLOR await giveaway.edit(embed=new_embed) await self.bot.db.update_guild_config( giveaway.guild.id, {'$set': { 'giveaway.ended': True }})
async def did_you_know(self, ctx, member: discord.Member = None): """ Did you know that if you stop talking, no one has to hear your annoying ass? """ await ctx.send( f"{member.mention if member else ''} https://youtu.be/wOf1RP4Cq4w", allowed_mentions=AllowedMentions(users=True))
async def _start(self): """Play the game""" await self.chat.send( f"{self._alive_game_role.mention} game has started! (Your private channels will be created shortly)" ) fmt = "\n".join(f"{player.role}" for player in self.players) msg = await self.info.send(f"Roles this game are:\n{fmt}") await msg.pin() while True: if await self._cycle(): break # The game is done, allow dead players to chat again for player in self.players: if player.dead: await self.chat.set_permissions(player.member, read_messages=True) # Send winners winners = self.get_winners() winner_msg = "Winners are:\n{}".format( "\n".join(f"{winner.member.mention} ({winner})" for winner in winners) ) await self.chat.send(winner_msg, allowed_mentions=AllowedMentions(users=False)) # Send a message with everyone's roles roles_msg = "\n".join( f"{player.member.mention} ({player})" for player in self.players ) await self.ctx.send( f"The game is over! Roles were:\n{roles_msg}\n\n{winner_msg}", allowed_mentions=AllowedMentions(users=False), ) async with self.ctx.acquire() as conn: query = "UPDATE players SET win = true WHERE game_id = $1 AND user_id = $2" await conn.executemany( query, [(self.id, player.member.id) for player in winners] ) await conn.execute( "UPDATE games SET day_count = $1 WHERE id = $2", self._day, self.id ) await asyncio.sleep(60) await self.cleanup()
async def on_message(self, message: discord.Message): command = await self.bot.get_context(message) if command.command == None: if message.author is not self.bot.user and self.bot.user in message.mentions: messageContent: str = message.content if message.content.find(str(self.bot.user.id)): messageContent = messageContent.replace( f"<@!{self.bot.user.id}>", "") if messageContent == '': return async with command.typing(): await message.channel.send( logic.generateOutput(messageContent), allowed_mentions=AllowedMentions(users=False))
def __init__(self): super().__init__(command_prefix="cc!", case_insensitive=True, allowed_mentions=AllowedMentions.none(), intents=INTENTS, activity=discord.Activity( type=discord.ActivityType.watching, name="People play CircuitCraft")) self.logging_hook = discord.Webhook.from_url( os.getenv("WEBHOOK"), adapter=discord.RequestsWebhookAdapter()) self.mc = McClient("~/circuitcraft", "[CircuitCraft] ", self) self.rc = McClient("~/verifycraft", "[Verification] ", self) self.db = Database()
async def register_role(self, ctx, reaction, role: discord.Role, message: discord.Message): data = json_open(reactrole_path) guild_id = ctx.guild.id guild_dict = data if not message: message = self.temp_message if not message: await ctx.send( "Please specify a message by adding message URL, message ID, or by setting a temporary message with `set_message` command." ) return if reaction.startswith('<'): reaction_name = re.findall(r":([^:]*):", reaction) reaction_name = reaction_name[0] else: reaction_name = reaction if str(guild_id) in list(guild_dict.keys()): channel_dict = guild_dict[str(guild_id)] else: channel_dict = {} if str(message.channel.id) in list(channel_dict.keys()): message_dict = channel_dict[str(message.channel.id)] else: message_dict = {} if str(message.id) in list(message_dict.keys()): react_role_dict = message_dict[str(message.id)] else: react_role_dict = {} allowed_mentions = AllowedMentions(roles=False) if str(reaction_name) in list(react_role_dict.keys()): registered_role = ctx.guild.get_role( int(react_role_dict[str(reaction_name)])) await ctx.send( f"Emoji {reaction} already registered to {registered_role.mention}", allowed_mentions=allowed_mentions) return elif str(role.id) in list(react_role_dict.values()): await ctx.send(f"{role.mention} already registered to {reaction}", allowed_mentions=allowed_mentions) return else: react_role_dict[str(reaction_name)] = str(role.id) message_dict[str(message.id)] = react_role_dict channel_dict[str(message.channel.id)] = message_dict guild_dict[str(guild_id)] = channel_dict data = guild_dict json_write(reactrole_path, data) await ctx.send( f"{role.mention} has been registered to {reaction} on message:\n{message.jump_url}", allowed_mentions=allowed_mentions) question = await ctx.send( "Would you like me to react to that message with the specified emoji?" ) emoji_list = ['✅', '❌'] for i in emoji_list: await question.add_reaction(i) def checker(reaction, user): return user == ctx.author and str(reaction.emoji) in emoji_list # This makes sure nobody except the command sender can interact with the "menu" while True: try: r, user = await self.client.wait_for("reaction_add", timeout=15, check=checker) if str(r.emoji) == "✅": await message.add_reaction(reaction) await question.delete() await ctx.send("Added reaction") break elif str(r.emoji) == "❌": await question.delete() await ctx.send("Reaction not added") break except asyncio.TimeoutError: break
async def create(self, ctx: commands.Context, *, time: UserFriendlyTime) -> None: """Create a giveaway Example: `!!giveaway create 3 days 5 $10USD` """ async with ctx.typing(): latest_giveaway = await self.get_latest_giveaway(ctx) if not latest_giveaway: try: winners = max(int(time.arg.split(' ')[0]), 1) except ValueError as e: raise commands.BadArgument( 'Converting to "int" failed for parameter "winners".' ) from e # Check if the giveaway exusts guild_config = await self.bot.db.get_guild_config(ctx.guild.id) if not guild_config.giveaway.channel_id: await ctx.invoke( self.bot.get_command('help'), command_or_cog='setgiveaway', error=Exception( 'Setup giveaways with setgiveaway first.')) return if not time.arg: raise commands.BadArgument( 'Converting to "str" failed for parameter "description".' ) description = ' '.join(time.arg.split(' ')[1:]) em = discord.Embed( title='New Giveaway!', description= f"__{winners} winner{'s' if winners > 1 else ''}__\n{description}", color=ACTIVE_COLOR, timestamp=time.dt) em.set_footer(text='End Time') role = await self.role(ctx) channel = await self.channel(ctx) emoji_id = await self.emoji(ctx) if isinstance(role, discord.Role): message = await channel.send( role.mention, embed=em, allowed_mentions=AllowedMentions.all()) elif isinstance(role, str): message = await channel.send( role, embed=em, allowed_mentions=AllowedMentions.all()) else: message = await channel.send(embed=em) await message.add_reaction(f'giveaway:{emoji_id}') await self.bot.db.update_guild_config( ctx.guild.id, { '$set': { 'giveaway.message_id': str(message.id), 'giveaway.ended': False } }) await ctx.send(f'Created: {message.jump_url}') self.bot.loop.create_task(self.queue_roll(message)) else: await ctx.send( 'A giveaway already exists. Please wait until the current one expires.' )