Advertisement
xosski

Discord 24/7 cog bot

Dec 25th, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.49 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. import sqlite3
  4. import wavelink
  5. import asyncio
  6. import logging
  7.  
  8. class TwentyFourSeven(commands.Cog):
  9. def __init__(self, client):
  10. self.client = client
  11. self.color = discord.Color.blue()
  12. self.logger = logging.getLogger(__name__)
  13.  
  14. # Ensure the 247 table exists with voice_channel_id
  15. with sqlite3.connect("247.db") as conn:
  16. c = conn.cursor()
  17. c.execute("""
  18. CREATE TABLE IF NOT EXISTS settings (
  19. guild_id INTEGER PRIMARY KEY,
  20. mode TEXT,
  21. voice_channel_id INTEGER
  22. )
  23. """)
  24. conn.commit()
  25.  
  26. @commands.command(name="247", aliases=["24/7"])
  27. @commands.cooldown(1, 5, commands.BucketType.user)
  28. async def twenty_four_seven(self, ctx, mode: str = None):
  29. """
  30. Set the 24/7 mode for the server.
  31. """
  32. if not ctx.author.guild_permissions.manage_guild:
  33. return await ctx.send(embed=discord.Embed(description="❌ You don't have the **Manage Guild** permission to use this command.", color=self.color))
  34.  
  35. if not ctx.author.voice or not ctx.author.voice.channel:
  36. return await ctx.send(embed=discord.Embed(description="❌ You must be in a voice channel to use this command.", color=self.color))
  37.  
  38. if not ctx.voice_client:
  39. return await ctx.send(embed=discord.Embed(description="❌ I am not in a voice channel. Use the `join` command first.", color=self.color))
  40.  
  41. if mode is None:
  42. return await ctx.send(embed=discord.Embed(description="❌ Please provide a mode: `enabled` or `disabled`.", color=self.color))
  43.  
  44. mode = mode.lower()
  45. if mode not in ["enabled", "disabled", "enable", "disable"]:
  46. return await ctx.send(embed=discord.Embed(description="❌ Invalid mode! Use `enabled` or `disabled`.", color=self.color))
  47.  
  48. mode = "enabled" if mode in ["enabled", "enable"] else "disabled"
  49. voice_channel_id = ctx.author.voice.channel.id # Store the current voice channel ID
  50.  
  51. with sqlite3.connect("247.db") as conn:
  52. c = conn.cursor()
  53. c.execute("SELECT mode FROM settings WHERE guild_id = ?", (ctx.guild.id,))
  54. result = c.fetchone()
  55.  
  56. if result:
  57. if result[0] == mode:
  58. return await ctx.send(embed=discord.Embed(description=f"❌ 24/7 Mode is already set to `{mode}`.", color=self.color))
  59. c.execute("UPDATE settings SET mode = ?, voice_channel_id = ? WHERE guild_id = ?", (mode, voice_channel_id, ctx.guild.id))
  60. conn.commit()
  61. await ctx.send(embed=discord.Embed(description=f"✅ Successfully updated 24/7 Mode to `{mode}` in <#{voice_channel_id}>.", color=self.color))
  62. else:
  63. c.execute("INSERT INTO settings (guild_id, mode, voice_channel_id) VALUES (?, ?, ?)", (ctx.guild.id, mode, voice_channel_id))
  64. conn.commit()
  65. await ctx.send(embed=discord.Embed(description=f"✅ Successfully set 24/7 Mode to `{mode}` in <#{voice_channel_id}>.", color=self.color))
  66.  
  67. @commands.Cog.listener()
  68. async def on_ready(self):
  69. """
  70. Reconnect to all enabled 24/7 guilds on bot startup.
  71. """
  72. await self.client.wait_until_ready()
  73.  
  74. if not wavelink.Pool.nodes.values():
  75. self.logger.warning("No Lavalink nodes connected. Retrying...")
  76. await asyncio.sleep(5)
  77. if not wavelink.Pool.nodes.values():
  78. self.logger.error("Lavalink nodes are still not connected. Exiting 24/7 reconnect process.")
  79. return
  80.  
  81. with sqlite3.connect("247.db") as conn:
  82. c = conn.cursor()
  83. c.execute("SELECT guild_id, voice_channel_id FROM settings WHERE mode = ?", ("enabled",))
  84. guilds = c.fetchall()
  85.  
  86. for guild_id, voice_channel_id in guilds:
  87. guild = self.client.get_guild(guild_id)
  88.  
  89. if guild is None:
  90. continue
  91.  
  92. voice_channel = guild.get_channel(voice_channel_id)
  93. if voice_channel is None:
  94. self.logger.warning(f"Voice channel {voice_channel_id} not found in guild {guild_id}. Skipping.")
  95. continue
  96.  
  97. # Check if the bot has permission to connect and speak in the channel
  98. if not voice_channel.permissions_for(guild.me).connect or not voice_channel.permissions_for(guild.me).speak:
  99. self.logger.warning(f"Missing permission to connect or speak in {voice_channel.name} ({voice_channel_id}) in {guild.name}.")
  100. continue
  101.  
  102. voice_state = guild.voice_client
  103. if voice_state is None:
  104. try:
  105. await voice_channel.connect(cls=wavelink.Player)
  106. self.logger.info(f"Reconnected to {voice_channel.name} in {guild.name}")
  107. except Exception as e:
  108. self.logger.error(f"Failed to connect to {voice_channel.name} in {guild.name}: {e}")
  109.  
  110. @commands.Cog.listener()
  111. async def on_wavelink_inactive_player(self, player):
  112. """
  113. Handle inactive players based on 24/7 mode settings.
  114. """
  115. guild_id = player.guild.id
  116.  
  117. with sqlite3.connect("247.db") as conn:
  118. c = conn.cursor()
  119. c.execute("SELECT mode FROM settings WHERE guild_id = ?", (guild_id,))
  120. result = c.fetchone()
  121.  
  122. if result and result[0] == "enabled":
  123. return # Stay in the voice channel
  124. else:
  125. try:
  126. await player.home.send(embed=discord.Embed(
  127. description="❌ The voice channel is inactive, and I have disconnected. To keep me connected 24/7, please enable 24/7 mode using `!247 enabled`.",
  128. color=self.color
  129. ))
  130. except Exception as e:
  131. self.logger.error(f"Failed to send message: {e}")
  132. await player.disconnect()
  133.  
  134. @commands.Cog.listener()
  135. async def on_voice_state_update(self, member, before, after):
  136. """
  137. Detect when the bot is kicked or disconnected from the voice channel.
  138. Reconnect if 24/7 mode is enabled.
  139. """
  140. if member.id == self.client.user.id: # Check if the bot is the one being updated
  141. if before.channel and not after.channel: # Bot was disconnected
  142. with sqlite3.connect("247.db") as conn:
  143. c = conn.cursor()
  144. c.execute("SELECT mode, voice_channel_id FROM settings WHERE guild_id = ?", (before.guild.id,))
  145. result = c.fetchone()
  146.  
  147. if result and result[0] == "enabled":
  148. voice_channel = before.guild.get_channel(result[1])
  149. if voice_channel:
  150. try:
  151. await voice_channel.connect(cls=wavelink.Player)
  152. await before.guild.text_channels[0].send(embed=discord.Embed(
  153. description=f"✅ Reconnected to <#{voice_channel.id}> to maintain 24/7 mode.",
  154. color=self.color
  155. ))
  156. except Exception as e:
  157. self.logger.error(f"Failed to reconnect to <#{voice_channel.id}>: {e}")
  158.  
  159. async def setup(client):
  160. await client.add_cog(TwentyFourSeven(client))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement