Discord.py clone entire server command - python

I am looking for a command that Clones the entire server and creates as a backup
Ik this a command
#bot.command()
async def copych(ctx, id: typing.Optional[int], *, channame="founders"):
if id == None:
chan = ctx.channel
else:
chan = bot.get_channel(id=id)
chan_perm = chan.overwrites
await ctx.guild.create_text_channel(name=channame, overwrites=chan_perm)
But this isn't what I was looking for

There is no "command" as such... :) But you can use boto3 and discord to backup the server to an s3 bucket.
import discord
import boto3
import json
client = discord.Client()
#client.event
async def on_ready():
print("Bot is ready")
#client.event
async def on_guild_available(guild):
# Create a backup of the guild data
backup = {
"guild_name": guild.name,
"guild_id": guild.id,
"guild_member_count": guild.member_count,
"guild_channels": [],
"guild_roles": []
}
# Add information about the channels in the guild
for channel in guild.channels:
backup["guild_channels"].append({
"channel_name": channel.name,
"channel_id": channel.id,
"channel_type": str(channel.type)
})
# Add information about the roles in the guild
for role in guild.roles:
backup["guild_roles"].append({
"role_name": role.name,
"role_id": role.id,
"role_permissions": role.permissions.value
})
# Save the backup data to a JSON file
with open("discord_backup.json", "w") as f:
json.dump(backup, f)
# Connect to the S3 bucket
s3 = boto3.client("s3")
# Upload the backup file to the S3 bucket
with open("discord_backup.json", "rb") as data:
s3.upload_fileobj(data, "my-s3-bucket", "discord_backup.json")
client.run("your-discord-token")
And here is a script to restore the server
import discord
import boto3
import json
client = discord.Client()
#client.event
async def on_ready():
print("Bot is ready")
# Connect to the S3 bucket
s3 = boto3.client("s3")
# Download the backup file from the S3 bucket
with open("discord_backup.json", "wb") as data:
s3.download_fileobj("my-s3-bucket", "discord_backup.json", data)
# Load the backup data from the JSON file
with open("discord_backup.json", "r") as f:
backup = json.load(f)
# Create a new Discord server using the backup data
guild = await client.create_guild(name=backup["guild_name"])
# Create the channels in the new server
for channel in backup["guild_channels"]:
if channel["channel_type"] == "text":
await guild.create_text_channel(name=channel["channel_name"])
elif channel["channel_type"] == "voice":
await guild.create_voice_channel(name=channel["channel_name"])
# Create the roles in the new server
for role in backup["guild_roles"]:
await guild.create_role(name=role["role_name"], permissions=discord.Permissions(role["role_permissions"]))
client.run("your-discord-token")

Related

Discord bot / commands not showing up

When I type / in my Discord server chat, the commands don't show up. I tried everything and don't know why it won't work. Here is the code of the bot:
import discord
import asyncio
from discord.ext import commands, tasks
import os
import random
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from discord import TextChannel
from youtube_dl import YoutubeDL
import sys
import spotipy
import spotipy.util as util
import youtube_dl
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=".", intents=intents)
# Set the intents for the bot
intents.members = True
intents.presences = True
intents.typing = True
intents.message_content = True
client = commands.Bot(command_prefix='.', intents=intents)
audio_data = None
CLIENT_ID = "YOUR_ID"
CLIENT_SECRET = "SECRET"
REDIRECT_URI = "http://localhost:8888/callback"
USERNAME = "your-username"
scope = "user-read-private user-read-playback-state user-modify-playback-state"
token = util.prompt_for_user_token(USERNAME, scope, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI)
spotify_api = spotipy.Spotify(auth=token)
players = {}
#client.event # check if bot is ready
async def on_ready():
print('Bot online')
#client.command()
async def entra(ctx):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
#client.command(name='leave', aliases=['esci', 'quit'], pass_context=True)
async def leave(ctx):
voice_client = ctx.voice_client
if voice_client is not None:
await voice_client.disconnect()
await ctx.send('๐Ÿค™')
else:
await ctx.send('๐Ÿ˜')
#client.command(name='avvia', aliases=['ascolta', 'play'], description="riproduce link youtube")
async def play(ctx, url):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(client.voice_clients, guild=ctx.guild)
# Check if the given url is a Spotify track or playlist
if "open.spotify.com/track/" in url:
# Extract the track id from the url
track_id = url.split("/")[-1]
# Get the track data from Spotify
track_data = spotify_api.track(track_id)
# Set the audio data to the track's preview url
audio_data = track_data["preview_url"]
await ctx.send("รจ possibile solo sentire i 30 secondi di preview di una canzone tramite link di spotify perche spotify รจ stronzo ๐Ÿ˜")
elif "open.spotify.com/playlist/" in url:
# Extract the playlist id from the url
playlist_id = url.split("/")[-1]
# Get the playlist data from Spotify
playlist_data = spotify_api.playlist(playlist_id)
# Get the playlist's track data
track_data = spotify_api.playlist_tracks(playlist_id)
# Set the audio data to the first track's preview url
audio_data = track_data[0]["preview_url"]
await ctx.send(
"รจ possibile solo sentire i 30 secondi di preview di una canzone tramite link di spotify perche spotify รจ stronzo ๐Ÿ˜")
elif "youtube.com" in url:
# The url is not a Spotify track or playlist, so use YoutubeDL to extract the audio data
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
audio_data = info['url']
else:
await ctx.send('๐Ÿ˜')
if not voice.is_playing():
# Play the audio data
voice.play(FFmpegPCMAudio(audio_data, **FFMPEG_OPTIONS))
voice.is_playing()
if ctx.message.author == "Aq3ila":
await ctx.send("musica di merda incoming ๐Ÿ’€๐Ÿ’€๐Ÿ’€")
else:
await ctx.send("๐ŸŽต")
return
else:
await ctx.send("impara ad'aspettare")
# command to resume voice if it is paused
#client.command()
async def riavvia(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if not voice.is_playing():
voice.resume()
await ctx.send('riavviando')
# command to pause voice if it is playing
#client.command()
async def pausa(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
await ctx.send('messo in pausa')
# command to stop voice
#client.command(name='ferma', aliases=['stop', 'annulla'], description="ferma la canzone in riproduzione")
async def stop(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
await ctx.send('๐Ÿ’ฅ๐Ÿ’ข๐Ÿ’ฅ๐Ÿ’ข')
client.run("YOUR_TOKEN")
I don't know why it won't work.
First of all, you've included your Bot Token in the bot.run(). Delete that and reset your token right now.
Next: All of your commands are text commands, i.e. They're triggered when a message has the bot prefix in it.
Slash commands are integrated into the Discord client itself. They don't need a message to trigger them but can be run directly from the client.
I'll show you the method I use to make slash commands, but there are other ways to do this.
To make a slash command, first have this in your on_ready:
#bot.event
async def on_ready():
#sync your commands and saves information about them in a var
synced = await bot.tree.sync()
#print how many commands were synced.
print(f"Synced {len(synced)} command(s)")
Afterwards, create commands with the #bot.tree.command decorator.
For example:
#bot.tree.command(name="command_nam", description="command_description")
async def unique_command_name(interaction: discord.Interaction):
#code here
Here, instead of Context or ctx, you're using the Interaction class. You can check out how Interactions work in the docs.
Edit: as stated in a comment down below, don't do this with bot's that have a lot of command that you restart often. It's just an alternative method for bot's that aren't general-purpose.

My discord.py discord bot keeps getting throttled by the Discord API/Cloudflare

Basically, my bot randomly gets banned for "exceeding the Discord API Ratelimits", but it accesses the Discord API once every HOUR. I host my bot on Replit. There is a 429 Too many requests error, and here are some of the error messages.
Access denied | discord.com used Cloudflare to restrict access.
The owner of this website (discord.com) has banned you temporarily from accessing this website.
The entire error message is written in HTML and it is just plopped into the Replit console, which makes it hard to read for me. Any help would be appreciated!
def getguildcount(guildid): #GETS guild member count from Hypixel API
with open("serverchannel.json", "r") as read_file:
data = json.load(read_file)
global guildname
guildname = data[guildid]['guildname']
data = requests.get(
url = f'https://api.hypixel.net/guild?key=NOT IMPORTANT&name={guildname}',
params = {
"key": "NOT IMPORTANT"
}
).json()
guild = data['guild']
guild = guild['members']
membercount = len(guild)
return membercount
def getservercount(): #gets member count in the discord server
for guild in bot.guilds:
membercount = guild.member_count
return membercount
def getdiscchannel(guildid): #gets discord channel from json file
with open("serverchannel.json", "r") as read_file:
data = json.load(read_file)
return data[guildid]['discchannel']
def getguildchannel(guildid): #gets guild channel from json file
with open("serverchannel.json", "r") as read_file:
data = json.load(read_file)
return data[guildid]['guildchannel']
async def countermainloop(): #loop that consistently updates channels
while True:
for guild in bot.guilds:
discordmemb = bot.get_channel(getdiscchannel(f'{guild.id}'))
guildmemb = bot.get_channel(getguildchannel(f'{guild.id}'))
guildmembers=getguildcount(f'{guild.id}') #gets guild member count
discmembers=getservercount() #gets discord member count
#edits both channels
await discordmemb.edit(name=f'Discord Members: {discmembers}')
await guildmemb.edit(name=f'Guild Members: {guildmembers}')
#Logs Changes in Console
tz_Ch = pytz.timezone('America/Chicago')
time_Ch = datetime.now(tz_Ch)
time = time_Ch.strftime("%H:%M:%S")
print(f'updated with {discmembers} discord members and {guildmembers} guild members at {time} CST in guild {guildname}')
await asyncio.sleep(3600)

Run discord bot/client from another file

How can i have bot code in one file but run the actual bot in another file (not cogs/extensions).
i need to run it in another file because of loop conflicts.
i tried importing client (variable of the bot constructor) and .start() on it but it didnt work, only the web server started.
example code:
in bot file:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print("Im ready!")
in another file (Sanic web app in my case):
from bot_file import client
import discord
from sanic import Sanic
app = Sanic()
app.run()
client.run("token")
I have cool solution for you
why Don't you make only 1 file that have all the code like this
import discord
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('inspire'):
quote = get_quote()
await message.channel.send(quote)
client.run('TOKEN')

How to I make a my discord bot join a voice channel *in a category*?

I'd like to write a bot with the ability to join; This is my code
import json
import discord
from discord.ext import commands
JSON_FILE = r"C:\JSON PATH"
bot = commands.Bot(command_prefix = "~")
with open(JSON_FILE, "r") as json_file:
TOKEN = json.load(json_file)["token"]
GUILD = json.load(json_file)["guild"]
bot = commands.Bot(command_prefix = "~")
#bot.event
async def on_ready():
print(f"{bot.user.name} launched and has arrived for further use")
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
await voice_channel.connect()
await ctx.send(f"I have joined: {voice_channel}")
#bot.command(name = "leave")
async def leave(ctx):
server = ctx.message.server
voice_client = bot.voice_client_int(server)
await voice_client.disconnect()
bot.run(TOKEN)
It can join usual channels but it cannot join channels in categories. Any advice on how to do that?
Thank you in advance
The problem is probably, that you are using an outdated version of discord.py since you are using server, which is deprecated since v1.0, and not guild. If you update it, it will probably work, because it worked for me too when I tried it.
To code it to automatically join the voice channel of the user executing the command, just use ctx.author.voice.channel:
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
if not ctx.author.voice is None:
await ctx.author.voice.channel.connect()
await ctx.send(f"I have joined your voice channel.")
else:
await ctx.send("You are not in a voice channel!")
References:
discord.Member.voice
Server is deprecated

How to set channel ID for multiple discord servers in python

I'm wondering how to send a message to a specific channel in discord.
Here's the code I have so far:
import discord
client = discord.Client()
#client.event
async def on_ready():
channel = client.get_channel(channelID)
await channel.send('hello')
client.run("---")
I want to have is so you run a command like !channel, and for that specific guild, the channel ID is set under the channelID variable. It has to be like this because if there are multiple servers, the admins can set where the message is sent.
So far, I found this post, but it's for javascript: Set channel id for DiscordBot for multiple servers
Here's the updated code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
client = discord.Client()
main_channels = {}
#bot.command()
async def channel(ctx):
guild_id = ctx.guild.id
channel_id = ctx.channel.id
main_channels[guild_id] = channel_id
await channel.send('hi')
client.run("TOKEN")
Any help is appreciated!
The command you're trying to implement is very simple; just create a dictionary that associates the guild's ID with the ID of the channel in which to send the message:
bot = commands.Bot(command_prefix = "$")
main_channels = {}
# The following command associates the ID of the guild to that of the channel in which this command is run.
#client.command()
async def channel(ctx):
guild_id = ctx.guild.id
channel_id = ctx.channel.id
main_channels[guild_id] = channel_id
# The following command sends a greeting message to the main channel set earlier for this guild.
#client.command()
async def greet(ctx):
guild_id = ctx.guild.id
channel_id = main_channels[guild_id]
channel = ctx.guild.get_channel(channel_id)
await channel.send("hi")
bot.run(token)
However, I suggest you consider using a permanent data archive, either an offline file (such as a json) or a real database, because once the bot is disconnected it is no longer possible to retrieve the data stored in that dictionary.
If you want to send the message to a specific channel, you have to do this:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('Online')
#client.event
async def on_message(message):
if message.content == "!channel":
channel = client.get_channel(SPECIFIC CHANNEL ID)
await channel.send("Hello")
client.run('TOKEN')
Else, if you want your bot to response in the same channel as the message, you can do this:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('Online')
#client.event
async def on_message(message):
if message.content == "!channel":
await message.channel.send("Hello")
client.run('TOKEN')

Categories