I'm trying to take certain roles when bot starting. First i need to take guild but i couldn't achieve it.
takenGuild = client.get_guild(myServerID)
takenGuild returning None
When i try to loop guilds
for guild in client.guilds:
print(guild.id)
it's not printing anything.
My whole code :
import discord
from discord.ext import commands, tasks
from discord.utils import get
client = commands.Bot(command_prefix = '.')
takenGuild = client.get_guild(123123123123123123)
print(takenGuild.id)
for guild in client.guilds:
print(guild)
print(guild.id)
client.run('Token')
You have to wait for the bot to be ready you can use this. FYI bot is more common now after the updates than client
import discord
from discord.ext import commands, tasks
from discord.utils import get
bot = commands.Bot(command_prefix = '.')
#bot.event
async def on_ready():
print("I am running on " + bot.user.name)
print("With the ID: " + bot.user.id)
print('Bot is ready to be used')
# after it is ready do it
takenGuild = bot.get_guild(123123123123123123)
print(takenGuild.id)
for guild in bot.guilds:
print(guild)
print(guild.id)
bot.run('Token')
Related
I'm trying to make a discord bot respond when someone makes laughing remarks but it infinitely sends gifs whenever someone types anything
code is as follows
import os
import discord
import random
from discord.ext import commands
import keep_alive
Bot_Token = os.environ['Bot_Token']
bot = discord.Client()
#bot.event
async def on_ready():
guild_count = 0
for guild in bot.guilds:
print(f"- {guild.id} (name: {guild.name})")
guild_count = guild_count + 1
print("AGOP_Bot is in " + str(guild_count) + " guilds.")
#bot.event
async def on_message(message):
if message.content == "AGOP~hello":
await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif")
if message.content == "Lmao" or "Lol" or "lmao" or "lol" and message.author.id != bot_id:
response_funny = ["https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif","https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif","https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif","https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png","https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif"]
await message.channel.send(random.choice(response_funny))
bot.run(Bot_Token)
keep_alive.py
import os
import discord
import random
from discord.ext import commands
# import keep_alive
Bot_Token = os.environ['Bot_Token']
bot = discord.Client()
...
#bot.event
async def on_message(message):
if message.content == "AGOP~hello":
await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif")
if message.content in ("Lmao" or "Lol" or "lmao" or "lol") and message.author.id != bot.user:
response_funny = ["https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif","https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif","https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif","https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png","https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif"]
await message.channel.send(random.choice(response_funny))
bot.run(Bot_Token)
# keep_alive.py
In addition to some formatting, I changed some of the variables for the API calls. I commented out the keep_alive.py as I assume you are using that to keep your code hosted on Repl.it or something, and you can just comment it back in. I was also able to get this code to work with my bot and execute as you want.
Im using the discord.py library and using replit for the bot, but my code doesnt work.
my code:
import os
import discord
from discord.utils import get
client = discord.Client()
#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.content == ";":
member = message.author
role = get(member.guild.roles, name="Recruiter")
await member.add_roles(role)
client.run(os.getenv("TOKEN"))
First of all, you're using client object and it is not a bot.
This is the way to create a proper bot (not client):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
You can't code reactions roles without reading the discord.py docs. It involves lots of stuff.
If you want to code it yourself, the only way is to learn and do.
i have only started to look around and figure how things work with discord.py bot. Tried making a bot that welcomes people in a certain channel. But no matter what I do, it doesn't seem to be working. The code executes and the on_ready fires. But its not welcoming the user like its supposed to. Can someone help?
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord import Color
import asyncio
import datetime
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
client=commands.Bot(command_prefix="-")
client.remove_command("help")
#client.event
async def on_ready():
print("Created by Goodboi")
print(client.user.name)
print("-----")
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server",)
embed.set_author(name=f"{member.mention}",icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow
channel = client.get_channel(id=) #usedid
await channel.send(embed=embed)
client.run('token') #usedtoken
Hi you have to get channel like this
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server",)
embed.set_author(name=f"{member.mention}",icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
channel = member.guild.get_channel(channel_id) #usedid
await channel.send(embed=embed)
The only thing you did wrong is passing no brackets to your datetime.datetime.utcnow "function" which gives out the following error:
TypeError: Expected datetime.datetime or Embed.Empty received builtin_function_or_method instead
If you put brackets behind the definition of your timestamp it should work:
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server", )
embed.set_author(name=f"{member.mention}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow() # Added brackets
channel = client.get_channel(ChannelID) # No "id=" needed
await channel.send(embed=embed)
You can also have a look at the docs: https://docs.python.org/3/library/datetime.html#datetime.datetime
This should work for you, though, can be improved in many ways, but if you asked for this, then here is it.
#client.event
async def on_member_join(member) :
channel = client.get_channel(CHANNEL ID) # First we need to get the channel we want to post our welcome message.
embed = discord.Embed(
colour=0xe8744f ,
description='Welcome to the discord server' ,
timestamp=datetime.utcnow()
)
embed.set_author(name=f'{member.mention}' , icon_url=f'{member.avatar_url}')
embed.set_footer(text=f'{member.guild}' , icon_url=f'{member.guild.icon_url}')
await channel.send(embed=embed) #Send the embed
I am currently trying to create my discord bot. sadly, this does not work and I have no Idea why...
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
there are NO errors. But no output aswell. I try making it join my vc by writing: .join
channel returns None, because ctx.message.author don't have voice attribute. Also, Client.join_voice_channel is deprecated since v1.0 (read here)
Instead of that, try this:
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.guild.get_member(ctx.author.id).voice.channel # This
await channel.connect()
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
Do client.add_command(join). You currently have the function for your command, but you haven't told the bot to recognize it as a command.
I'm fairly new at making a discord bot. I have created a method to get a list of all the members in the server the bot is connected to. This method works fine. However, I am also trying to get the bot to accept commands. I am having a lot of trouble with this and I keep seeing that I should use commands.Bot for this instead of Client. I can't figure out how to make my original method work with commands.Bot though. Any help would be appreciated!
import os
import discord
import csv
from collections import defaultdict
from discord.ext import commands
intents = discord.Intents.all()
client = discord.Client(intents=intents)
outP = open("giveawayList.txt", "w")
bot = commands.Bot(command_prefix='!')
#client.event
async def on_message(message):
if message == "!test":
await message.channel.send("you failed the test")
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild: \n'
f'{guild.name} (id: {guild.id})'
)
count = 0
for guild in client.guilds:
for member in guild.members:
print(member)
if 'Bots' not in str(member.roles):
print(member.name, ' ')
outP.write(member.name)
outP.write("\n")
count += 1
print('Number of members: ' + str(count))
It is good to use commands.bot instead of Client because it is an extended version, as it inherits all the functionalities from Client.
I see you have tried to migrate from the use of Client to using commands.bot, but have a few things in mind:
You do not want to use both at the same time, so this is wrong:
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!')
You should keep only the bot one.
Apart from that, you gotta replace the client from the decorators and the calls inside the function. Your corrected code should look something like this:
import os
import discord
import csv
from collections import defaultdict
from discord.ext import commands
intents = discord.Intents.all()
outP = open("giveawayList.txt", "w")
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.event
async def on_message(message):
if message == "!test":
await message.channel.send("you failed the test")
await bot.process_commands(message)
#bot.event
async def on_ready():
for guild in bot.guilds:
if guild.name == GUILD:
break
print(
f'{bot.user} is connected to the following guild: \n'
f'{guild.name} (id: {guild.id})'
)
count = 0
for guild in bot.guilds:
for member in guild.members:
print(member)
if 'Bots' not in str(member.roles):
print(member.name, ' ')
outP.write(member.name)
outP.write("\n")
count += 1
print('Number of members: ' + str(count))
So, regarding your questions, i am gonna answer them one by one :
1- client and bot are not diffrent at all, that means you shouldn't have any problem using the same functions on both(and neither are better than each other, meaning both will do the same stuff)
2- now to get your bot to receive/accept commands, you can use the await function, which basically waits for a command to be trigerred and will give out the output.
For example :
#Client.command()
async def botping(ctx):
await ctx.send(f"The bot's ping is {round(Client.latency*1000)} ms")
This command here (for example):
We are defining a command called "botping" and we are passing the ctx wich is the context the bot is writing, the you have the await wich will trigger the command when you type "prefix"botping in chat.
Hopefully this helped you a little bit about the concept of taking commands and that there is no diffrence between client and bot
For further information, i suggest that you check out the discord.py documentation:
https://discordpy.readthedocs.io/en/latest/index.html