Advertisement
xosski

Discord voice bot

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