#discord-bots
1 messages · Page 511 of 1
how can i remove my bot from a server, but i am not owner of the server
Get the corresponding guild object then use leave method of it
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
ok ty
hi, how can i get a member's account creation date with id?
@commands.command()
async def tost(ctx, * args, time):
age = datetime.utcnow() - #member's account creation date
await ctx.send(age)
!d discord.Member.created_at
property created_at```
Equivalent to [`User.created_at`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.created_at "discord.User.created_at")
alright thanks
@commands.command(aliases=["whois"])
async def userinfo(self, ctx, member: discord.Member = None):
if member == None:
member = ctx.author
roles = [role for role in member.roles][1:]
embed = discord.Embed(
description = f'**User Infomation - **{member.mention}',
colour=member.color,
timestamp=ctx.message.created_at
)
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(text=f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)
embed.add_field(name='ID:', value=f'`{member.id}`')
embed.add_field(name='Nickname:', value=member.display_name)
embed.add_field(name='Created at:', value=member.created_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name='Joined at:', value=member.joined_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name=f'Roles ({len(roles)})', value="\n".join([role.mention for role in roles]))
embed.add_field(name='Top Role:', value=member.top_role.mention)
embed.add_field(name = 'Bot:', value = member.bot)
await ctx.send(embed=embed)
i want to change the time from utc to ptc
how would i do that
Error:Ignoring exception in on_raw_reaction_remove Traceback (most recent call last): File "C:\Users\denis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 312, in _run_event await coro(*args, **kwargs) File "C:\Users\denis\OneDrive\Desktop\Developement\Discord Bot\cogs\reaktions-rollen.py", line 53, in on_raw_reaction_remove if role is not None: UnboundLocalError: local variable 'role' referenced before assignment
Code:```py
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
message_id = payload.message_id
if message_id == 876220796081684541:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, self.client.guilds)
if payload.emoji.name == ':mailbox_with_no_mail:':
role = discord.utils.get(guild.roles, name='「Ping » News」')
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.remove_roles(role)
print("done")
else:
print("Member not found.")
else:
print("Role not found.")```
because did you set the variable 'role' to if payload.emoji.name == ': mailbox_with_no_mail:': and called it to if role is not None:
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
message_id = payload.message_id
if message_id == 876220796081684541:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, self.client.guilds)
role = discord.utils.get(guild.roles, name='「Ping » News」')
if payload.emoji.name == ':mailbox_with_no_mail:':
if role:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member:
await member.remove_roles(role)
print("done")
else:
print("Member not found.")
else:
print("Role not found.")
you can try something like that
if you see we have define the role before "if statements"
worked, but now it says "Role not found."
make sure you have define the role
you can try this way role = guild.get_role(role id)
And here you can check if user have the role
if member:
if role in member.roles:
await member.remove_roles(role)
I do not want to confuse you with all this, it is just better to write them correctly and with the right bases.
url="attachment://name.png"
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
@visual island cant understand sry.
huh?
There are several called "kyle" previous wrote a problem I read it and deleted it. I wanted to answer him but I probably made the wrong mention. Excuse me.
How do I get the response message of a command to be eliminated in a certain time?
so there is a keyword that you can use called delete_after= here is an example
await ctx.send("hello", delete_after=5)
and that will then delete the message after 5 seconds
thanks
whats the line to get guild's profile url
wdym by guild's profile
yeah but you have to call that on a guild object
yea got it ty
Its not just accessing icon_url
As it isn't a link, rather an Asset object
you can cast str on it to get the CDN url
nah i jhust used it as an icon
@client.command()
async def memberstat(ctx):
for member in ctx.guild.members:
try:
print(f"{member.name}")
userAvatarUrl = member.avatar_url
print(userAvatarUrl)
why does this only get the avatar of 1 person
instead of every member
Im make discord bot "마시(masi)"
Discord.Py it's hard
OMG
🤦♂️
There's no point of using try and except here
if you have basic knowledge about Python , async/await syntax and give some time to reading the docs its really easy
Hmmmmmmm...
Im dont py code study....
걍 돼는데로하는뎅..
Zzz
I don't know what
Omg
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
How do I make the bot send emojis?
ok
await ctx.send(":rofl:"), the bot will send 🤣
u mean py await ctx.send("🤣")
i dont think you can do those things with a bot
how can i make my bot reply to a message that triggers an action? for example, if i were to type {prefix}command, it would react to that message with an emoji, i was thinking ctx.author.message.add_reaction(emoji) but that didnt work, any ideas?
guild = str(ctx.guild.id)
try:
gcid = self.giveawaychan[guild]
oldgiveawaymsgid = self.giveawaychan[guild]["giveawaymessageid"]
oldgiveawaychannelid = self.giveawaychan[guild]["giveawaychannelid"]
oldgiveawaytime = self.giveawaychan[guild]["time"]
except KeyError:
gcid = {}
oldgiveawaychannelid = {}
oldgiveawaymsgid = {}
oldgiveawaytime = {}
ogchannel = self.bot.get_channel(oldgiveawaychannelid)
ogmsg = await ogchannel.fetch_message(oldgiveawaymsgid)
currenttime = datetime.datetime.utcnow()
ogtime = ogmsg.created_at + datetime.timedelta(seconds = oldgiveawaytime)
print(ogtime-currenttime)
if ogtime > currenttime:```
for line `ogchannel = self.bot.get_channel(oldgiveawaychannelid)` it raises an error `TypeError: unhashable type: 'dict'`
Forgot or u don't know 
Does it apply if the bot plays music from your own system (your own files), and is not affiliated to youtube by any means?
Therefore, this applies to youtube most likely, with youtube_dl. I don’t know about Soundcloud or Spotify but that’s not a great idea either.
can we still use discord.py to make own bot?
Ahh ic
People made extensions for it.
The creator of it said he won’t support it anymore, but made it open source I think.
But it’s far from being dead.
anymore?
The community makes extensions of it
wasn't it always open source?
so we use the extensions
I think yeah LOL
ye
It was always
Yes we do.
discord_components is such a good one for buttons
hi
We hv to include slash cmds?
discord.py doesn’t have slash commands sadly
But some extensions are including them.
I think it’s called discord-slash
you could use forks though
Ahh ic
what are forks? Extensions?
GitHub forks.
Forking it from github
oooh
alts
!pypi disnake is a fork of dpy.
you could say that yes
ye
so no more discord.py updates?
ye seems like it
oh sed I was hoping to get components and slash commands in discord.py itself
ye
Disnake has that.
no sadly, we have to rely on forks and extensions
You can use extensions as well.
but discord.py is good
Which one is the best for slash and buttons though? I never found one that takes everything
always better to have everything at one place
!pypi dislash.py is great for interactions and components.
that's what I'm doing rn
but with extensions diff. people can be using diff. extensions. Having them in discord.py will standardize it
Most of the forks are the exact same syntax as dpy, just with a different name.
true but still...
If we use multiple forks at the same time, does it affect the functions you call? Does it execute the command twice for example?
Well, most forks support slash commands, buttons and application commands.
O wait, you need to call them.
Though, I highly promote disnake. It's really great and stable.
I’ll try it out.
@hard trail Sorry bro for the late Reply Actually I went outside my home because of some work
I don't why it's not working
Oh yeah speaking of interactions, can buttons have custom colors or there’s only 4? (Blue, red, green and grey)
i believe it's only those 4
That’s very unfortunate.
Basically what they want is 1,000 people to spam their server asking for it. (I'm kidding)
I thought of doing a minigames with buttons, but now I think about it, I don’t think you can restrict the button to others (like permission) so this might be difficult.
That’s from the buttons feature or you meant checking manually in code?
By the way, Discord has answered this as well
What is Bot?
client
Is that your commands.Bot instance?
Hmmm I shall take a look very closely for what’s coming next.
yes
Is that inside a cog?
yes
await **self.**Bot.wait_for()
If you're confused you can have a look at this repository explaining how to use cogs with examples.
https://github.com/ScopesCodez/discordpy-cogs
Example for using cogs in discord.py. Contribute to ScopesCodez/discordpy-cogs development by creating an account on GitHub.
thank you works
No problem.
By the way Scoopy
Yes?
async def giveaway(self, ctx):
guild = str(ctx.guild.id)
try:
gcid = self.giveawaychan[guild]
except KeyError:
gcid = {}
if not gcid:
# do something
else:
print("else")
try:
gcid = self.giveawaychan[guild]
oldgiveawaymsgid = self.giveawaychan[guild]["giveawaymessageid"]
oldgiveawaychannelid = self.giveawaychan[guild]["giveawaychannelid"]
oldgiveawaytime = self.giveawaychan[guild]["time"]
except KeyError:
gcid = {}```
the else isnt getting triggered
Could you please DM me the theme's name and the font family you use? I really love them.
Are we allowed to ask questions concerning ffmpeg for a bot if it’s not affiliated with youtube by any means?
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
If the songs are from YouTube then no.
I didn’t get them from youtube at all
I got them from that website where you can download sound effects
Then gcid returns None.
Then I think you can.
Ofc
But unfortunately, I cannot help you since I'm not familiar with Ffmpeg.
No problem.
Let’s hope someone is familiar with it.
.
Ask in the desired channel 
async def getavatar(ctx, member: discord.Member = None):
if not member:
member = ctx.message.author
avatarURL = member.avatar_url
return avatarURL```
```py
avatarURL = member.avatar_url
AttributeError: 'Context' object has no attribute 'avatar_url'```
does anyone know what i did wrong here
show how you're calling the function
Well it is related to discord bots..
What anand said, plus, no need to get the author of the message. commands.Context has an author attribute.
ctx.author will work as well.
how do i hyperlink text?
[text](url)
@commands.command(name = 'ship', aliases = [])
async def ship(ctx, user1: discord.Member = None, user2: discord.Member = None):
user1avatar = await myclass.getavatar(ctx, user1)
user2avatar = await myclass.getavatar(ctx, user2)
await ctx.send(f"***There is already an active giveaway.\nYou can only create a new giveaway when the current active giveaway ends.\n[Current Giveaway](oldgiveawaymessageid.url) ends in {timeLeft}***" like that?oldgiveawaymessageid is a message
Hyperlinks only work in embed descriptions
jump_url*
No, not only descriptions. Fields values as well.
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
comes like this
Is this a field value or an embed description?
Here
hyperlink dont work in normal msgs?
Not in python, no.
sad
I think it does in djs.
ye it does
Oh I never knew it was possible to hyperlink in a normal message
sorry im not very good at python yet
@bot.command(aliases=['em'])
async def create_embed(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
try:
await ctx.send('Waiting for a title')
title = await bot.wait_for('message', timeout=30.0, check=check)
except:
await ctx.channel.purge(limit=2)
await ctx.send('Timeout', delete_after=5)
try:
await ctx.send('Waiting for a description')
desc = await bot.wait_for('message', timeout=30.0, check=check)
except:
await ctx.channel.purge(limit=4)
await ctx.send('Timeout', delete_after=5)
embed = discord.Embed(title=title.content, description=desc.content, color=0x72d345)
await ctx.send(embed=embed)
How can I stop it to ask for description if the title isn't given?
Is that function in a class
its not working
its not showing up
Where do you have it?
its a class for a cog
so all the commands are in it, and the getavatar function also is
works in embed description right?
Certainly.
Oh
That's not the right way to call class functions
You can just ignore the self part
So, self.get_avatar(ctx, ...)
oh
@dapper cobalt is there a reason to why a command can't run if it's using a .json
Elaborate?
cant we hyperlink a certain text in the description?
I have a data file and it works fine when I use the path to that file on my computer but once I push it out to github, the command doesn't function
You can.
how?
Plz help with this
Just put return inside except: ig
Define the title variable as None before the try...except and then before the try of the description part check if title:.
@dapper cobalt
embed = discord.Embed(description = f"***There is already an active giveaway.\nYou can only create a new giveaway when the current active giveaway ends.\n[Current Giveaway]{(ogmsg.jump_url)} ends in {timeLeft}***") this doesnt hyperlink the [Current Giveaway]
Or this.
Show me a screenshot.
Are you hosting the bot on GitHub?
{(ogmsg.jump_url)}, This part doesn't sound right
Heroku
Using my repository on github
Well, I don't think the path of the file on heroku is same as it is on your computer.
You swapped the brackets and the curly ones
Try removing both bold and italic markdowns.
I changed the name to just "data.json" instead of my computer path
It still doesn't work
I didn't notice that.
same
You swapped the () with {}.
Is the data.json and the python file in the same directory?
ah , thanks ❤️
No problem.
Yes
Under my cogs folder
Try cogs/data.json.
Ok will do
How to delete the trigger of the command?
await ctx.message.delete()
i think
im still not really sure how to fix it
i tried adding self to it but it still showed as 'self' is not defined
the same error as before came up when i moved the function out of the class
Did you initialize your cog's class?
sorry wdym?
Do you have
def __init__(self, bot): self.bot = bot
Under the class?
Hi, Im new to python
what about delay?
delay for what?
deleting the trigger
u could use asyncio.sleep
Delay =
its a coro though so dont forget to await it
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.

@commands.command()
@commands.has_role("giveaway")
@commands.has_permissions(administrator=True)
async def gstart(self, ctx, mins: int, prize):
embed = discord.Embed(title="🎉 GIVEAWAY🎉", description=f"{prize}", color=discord.Color.random())
end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins)
embed.add_field(name="Ends at:", value=f"{end}UTC")
embed.set_footer(text=f"Ends {mins} minutes from now")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await ctx.send(f"congratulations! {winner.mention} won {prize}")
```help please
discord.ext.commands.errors.CommandNotFound: Command "gcreate" is not found
Ignoring exception in command gstart:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bots\studybot\cogs\events.py", line 29, in gstart
users = await new_msg.users().flatten()
AttributeError: 'ComponentMessage' object has no attribute 'users'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ComponentMessage' object has no attribute 'users'
what does new_msg.users mean?
i want to see who reacted to that emoji
help
what
hm
Error is self explanatory
@tropic briar that channel got hidden for me :(( cooldown huh
how to fizx
Hmm
It means you used tabs/spaces in a bad way
yes
Just re-indent the pyflakes I guess
async def kick(self, ctx, member: discord.Member, reason="No Reason"):
if member == None:
embed = discord.Embed(f"{ctx.message.author}, Please enter a valid user!")
await ctx.reply(embed=embed)```
how xd
done i did back space and then enter it fixed
where
Thats the discord.Reaction class. Ur tryna get a list of users that reacted using the discord.Message class which doesnt exist
the command?
ok
wdym idk lol
idk xd
indents
where to use
the line that caused the syntax error
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await discord.reaction.flatten()
winner = random.choice(users)
await ctx.send(f"congratulations! {winner.mention} won {prize}")
im bit confused
How do I remove a reaction with the following info:
message ID
reactor ID
name/unicode of emoji
discord.p
yes? old one was worse
else:
guild = ctx.guild
embed = discord.Embed(title="Kicked!", description=f"{member.mention} has been kicked!!", colour=discord.Colour.blue(), timestamp=datetime.datetime.utcnow())
embed.add_field(name="Reason: ", value=reason, inline=False)
await ctx.reply(embed=embed)
await guild.kick(user=member)```
whats better in the rewrite
im confused can anyone help me plsssss
Why the bot isnt responding?
@bot.group(invoke_without_command=True)
async def help(ctx ):
em= discord.Embed(
title= "Help",
description="Use +help <command> for extended information on a command.",
color=0xFFFFFF
)
em.add_field(name = "Moderation", value = "Will be added soon.")
em.add_field(name = "**Embed**", value = "Creates embed.")
em.add_field(name = "**Music**", value = "Will be added soon.")
await ctx.send(f"{ctx.author.mention}", embed= em)
any error?
do u used on_command_error?
IDsareintsnotstringsserverwas changed toguild
More info: https://discordpy.readthedocs.io/en/stable/migrating.html
nope
alright thanks
i think it should be indentation error
.
bro it works fine
just responding on events
How do I remove a reaction with the following info:
message ID
reactor ID
name/unicode of emoji
Might be because of the @bot.group(invoke_without_command=True)
help_command = None?
yep
@bot.group(invoke_without_command=True)
async def helpi(ctx):
em = discord.Embed(
title="Help",
description="Use +help <command> for extended information on a command.",
color=0xFFFFFF
)
em.add_field(name="Moderation", value="Will be added soon.")
em.add_field(name="**Embed**", value="Creates embed.")
em.add_field(name="**Music**", value="Will be added soon.")
await ctx.send(f"{ctx.author.mention}", embed=em)
```this works fine
any command isnt working
did i messed up anything here?
bot = commands.Bot(command_prefix= '+' , intents=intents, activity=activity, status=discord.Status.online)
nope
yes i think
did u do bot.remove_command("help")
yes
hm
Guys, how do i get the role id here?
@client.command()
async def customrole(ctx, rolename: discord.Role=None, hexcode: discord.Color=None):
if ctx.message.channel.id == 893572364858699796:
if hexcode is None:
await ctx.send("Enter a hexcode!")
return
if rolename is None:
await ctx.send("Enter the role name!")
return
await open_account(ctx.message.author)
await open_account2(ctx.message.author)
with open("roles.json", "r") as f:
users = json.load(f)
user = ctx.message.author
if users[str(user.id)]["roles"] == 1:
await ctx.channel.purge(limit=1)
await ctx.send("You have reached the rate limit of custom roles!", delete_after=5)
return
member = ctx.message.author
await ctx.guild.create_role(name=rolename, color=hexcode, permissions=discord.Permissions(read_messages=False))
await ctx.channel.purge(limit=1)
role = discord.utils.get(ctx.guild.roles, name=rolename)
await member.add_roles(role)
await role.edit(position=60)
await ctx.send(f"Successfully created {rolename} role for you!", delete_after=5)
with open("roles.json", "r") as f:
users = json.load(f)
users[str(user.id)]["roles"] += 1
with open("roles.json", "w") as f:
json.dump(users, f)
with open("botrole.json", "r") as f:
roleid = json.load(f)
role2 = discord.utils.get(ctx.guild.roles, id=rolename.id)
print(role2)
print(type(role2))
roleid[str(ctx.message.author.id)]["roleid"] += role2
with open("botrole.json", "w") as f:
json.dump(roleid, f)
Hey @solemn grove!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Roleid?
yes
he already did that though
in the args or what or when ur invoking the command?
i not got my question answer
i am confused 🥲
It creates a role for the user and i want to get the id of that role
o
checkout my code
.
add this to your bot constructor
help_command=None
@boreal ravine
not only the help cmd all the commands isnt working
i see
plz take a look in my code
remove the 22 line
and add this to the bot constructor once
import discord
from discord.ext import commands
import asyncio
import datetime
import random
class events(commands.Cog):
def __init__(self, bot):
self.client = bot
@commands.command()
@commands.has_role("giveaway")
@commands.has_permissions(administrator=True)
async def gstart(self, ctx, mins: int, prize):
embed = discord.Embed(title=":tada: GIVEAWAY:tada:", description=f"{prize}", color=discord.Color.random())
end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins)
embed.add_field(name="Ends at:", value=f"{end}UTC")
embed.set_footer(text=f"Ends {mins} minutes from now")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction(":tada:")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await ctx.send(f"congratulations! {winner.mention} won {prize}")
def setup(bot):
bot.add_cog(events(bot))
can anyone help me
whats the error?
C:\bots\studybot\venv\Scripts\python.exe C:/bots/studybot/main.py
bot is ready
Ignoring exception in command gstart:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bots\studybot\cogs\events.py", line 29, in gstart
users = await new_msg.users().flatten()
AttributeError: 'ComponentMessage' object has no attribute 'users'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ComponentMessage' object has no attribute 'users'
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
embed = discord.Embed(title='**Close Combat Esports®**', description = '**My prefix is `+`\nYou can type `+help` for more info.**', color=0xFFFFFF)
await message.channel.send(embed=embed)
I just removed this and the bot works perfectly
Why is it so?
i think u overided on_message
idk, why this happens -_-
send code
put await bot.process_commands(message) on the bottom of the event
or change the decorator from @bot.event to @bot.listen()
can u help me pls
didnt worked
code
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
embed = discord.Embed(title='**Close Combat Esports®**', description = '**My prefix is `+`\nYou can type `+help` for more info.**', color=0xFFFFFF)
await message.channel.send(embed=embed)
await bot.process_commands(message)
import discord
from discord.ext import commands
import asyncio
import datetime
import random
class events(commands.Cog):
def __init__(self, bot):
self.client = bot
@commands.command()
@commands.has_role("giveaway")
@commands.has_permissions(administrator=True)
async def gstart(self, ctx, mins: int, prize):
embed = discord.Embed(title="🎉 GIVEAWAY🎉", description=f"{prize}", color=discord.Color.random())
end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins)
embed.add_field(name="Ends at:", value=f"{end}UTC")
embed.set_footer(text=f"Ends {mins} minutes from now")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await reaction.users().flatten()
# users is now a list of User...
winner = random.choice(users)
await ctx.send(f"congratulations! {winner.mention} won {prize}")
def setup(bot):
bot.add_cog(events(bot))
```help pls
C:\bots\studybot\venv\Scripts\python.exe C:/bots/studybot/main.py
bot is ready
Ignoring exception in command gstart:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bots\studybot\cogs\events.py", line 29, in gstart
users = await new_msg.users().flatten()
AttributeError: 'ComponentMessage' object has no attribute 'users'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ComponentMessage' object has no attribute 'users'
Process finished with exit code -1
How hard is it to make a bot to remove a role simultaneously with another?
For example, to make members automatically lose a role when they lose the server booster role?
@spring flax ?
What's wrong with it
Same problem the commands aren't working after adding it
quite easy well for me
Just remove the await bot.processs...
Ane change the decorater to @bot.listen()
bcuz the indent is wrong
I'm tryna take two consecutive messages as a second input
But the second part does trigger
Lemme show what I'm tryna do just a sec
async def on_message(message):
if message.author==client.user:
return
if message.content.startswith('BB'):
if message.content==('BB test'):
await message.channel.send('you have requested a test session, are you sure you wish to proceed')
async def on_message(cons_message):
if cons_message.content==('yes'):
await cons_message.channel.send('you have just confirmed that you requested a test session are you sure regarding your current course of action?')
@bot.listen()
async def on_message(message):
if bot.user.mentioned_in(message):
embed = discord.Embed(title='**Close Combat Esports®**', description = '**My prefix is `+`\nYou can type `+help` for more info.**', color=0xFFFFFF)
await message.channel.send(embed=embed)
@spring flax
what'd be the right way to do this?
like two consecutive command thingies but the second one only triggers if the first one was used....first
It can be the r in Esports
Command groups?
@client.command()
@client.has_permissions(ban_members = True, kick_members = True)
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` Why the permission thing is not working
welp, how can i make a command such that if it is not allowed by mods it cant be used
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
hmm
Removed it but got the same error
i think this doesn't works
What do you mean?
You did client.has_permissions
Lemme try and see if it works
client is the bot right?
@client.command()
@discord.ext.commands.has_permissions(ban_members = True)
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` Everything looks alright
Built-in Checks for the commands extension of discord py - Checks.py
why did you use the discord.ext?
thats the extension
check the gist
@client.command()
@commands.has_role("Mod")
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` but the command part?
like I don't think it should be commands
Have you ever even bothered looking at the docs
It's correct, commands is how it's supposed to be
how to check if a user have a role in if else?
@commands.has_role(your_role)
if roleobj in member.roles
Or this
Depends what you want
i want to check in if conditions
how do I remove a reaction w/ a RawReactionActionEvent
you can use .remove on a reaction, but not a raw reaction
You have the user that reacted, you also have the message and the reaction that got added, so just get the Message object along with the Member object and then remove the reaction for the member
if "Giveaway Handler" in (r.name for r in ctx.author.roles)
I'm not on pc rn so i can't spoonfeed that much
@client.command()
@commands.has_role("Mod")
@commands.has_role("Admin")
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` So this is what I have now but it works when I have the admin role but it doesn't even when I have Mod role
So it works when I have Admin but now when I have Mod
await bot.get_channel(reaction.channel_id).get_message(reaction.message_id).remove_reaction(reaction.member, reaction.emoji.name)
``` something like this?
!d discord.ext.commands.has_any_roles
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
so How should I put role names in that parenthesis
Like how you've done it before
ok
AttributeError: 'TextChannel' object has no attribute 'get_message'
i thought it did
Fetch it
alr
.get_ methods only work for the bot because they use the bot's cache
channel_class = await bot.get_channel(reaction.channel_id)
message_class = await channel_class.fetch_message(reaction.message_id)
await message_class.remove_reaction(reaction.member, reaction.emoji.name)
TypeError: object TextChannel can't be used in 'await' expression
ill try remove the await
oh
Emoji is first, member second
wrong way around
hey! the discord.py part worked, thanks.
i just need to fix the sql part
For that in #databases
yeah ik
@client.command()
@commands.has_any_role("Admin", "mod", "Owner")
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
``` Why is this not working even when I have the Mod and Admin role
Typehint amount with int
@tropic briar
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx,amount : int):
await ctx.channel.purge(limit = amount)
yes
why you are not using roles
instead of permissions use roles
ok
cause my bot is in 95 servers @tropic briar
and it was old code
oh yeh
XD
lemme try now
ye send screenshot
@clear.error
async def clear_error(ctx, error):
if isinstance(error,commands.MissingRequiredArgument):
await ctx.send('Please specify the amount of message to delete')
error handling
alright it's working
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
So do you also know How are music bots made ?
against terms of Discord Tos
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
So How can I make a music bot then
yes but i can help u
i can help u dms?
dm
accept frnd req
i will provide everything
someone pls help 😄 I need the code to remove a role once another is removed
please ❤️
is there any way to get the channel id with channel name?
Make a list of all the roles id, when user reacts define a variable that holds this [for role in user.roles if role.id not in all_roles_id_here] where user should be the one that reacted, that will return a list of roles, then just get the role that you want to add and add it to the list and then use .edit(roles=roles) on the member where roles is your list of roles
I gave u the idea you do the code yourself
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
guild = ctx.message.guild
channel_name = str(ctx.message.author).split("#")[0] + "-bots"
channel_list = ([i.name for i in guild.channels])
channel = discord.utils.get(ctx.guild.channels, name=channel_name)
channel_id = channel.id
look i did this
but that's returning none
but that channel exists
and the name is correct too
Try printing everything
alright
Nvm i just spot the error
i have 2 async commands and i can only use 1 if i delete i also have 1 prefix which is a . how do i make it so i canuse 2 for both commands
oh, what is that?
help pls
Since it's a command make it take the channel param
??
you want two prefixes?
i have to commands which are async and only one works idk why
i dont got but its for all ocdes
If u don't got the code we can't help u
wat
We have no way of knowing what's causing the error without having any example/proof to look at
sorry, i didn't understand
asynf def your_cmd(ctx, channel: discord.TextChannel)
oh
Then use it on the channel
alright
Actually wait that will return the TextChannel object that ur looking for already
So u don't have to use utils to get it anymore
uhm so?
i have 2 async functions the bot can count to 10 and the other one send s arandom message if i take the count to 10 bot away adn delete it the other one works but if i keep the other one the count to 10 wont work
i want to fetch the channel's id by it's name
Well isn't that what they're looking for
even if it's not the needed one
If you have the TextChannel object you don't have to bother with that
channel_name = str(ctx.message.author).split("#")[0] + "-bots" makes me think we're looking for a very specific channel

ah yeah
but that's not the point
(replace str(ctx.author) with ctx.author.name)
Yeah I'll need to see the code to know what you're doing
so what do i do now?
Im finally back
the server that tried to help me make a gdps with a discord bot
This time I want to link my discord bot to my mc aternos server
what da
I know it is possible, I just don't know how to do it
I've seen it before
how to get channel id by channel name?
So like have your bot in a minecraft server?
If you're using Java it should be fairly easy. Idk about Python though. There might be an API or something that could help you.
@somber tree use discordRCV https://www.spigotmc.org/resources/discordsrv.18494/?__cf_chl_jschl_tk__=pmd_pisZvTLtBCJnbYj.ybgtlEgAOwLRe6yN2qZUBHLm4so-1633163467-0-gqNtZGzNAfujcnBszQfl
Not really but it announces updates to my mc server
this is for discord-minecraft integration
Ive got code to connect a python bot to mc server without anything server side
Monitors chat n such, two way. If thats your goal?
please give me a line of code to remove a role once another is removed D:
So you'll need some form of server plugin then
except it's gonna be kinda tricky cuz it's bedrock edition and I don't use server plugins
my servers are usually survival ones
Well either you connect with something, or use a server side plugin
I'll try
@client.command()
async def topic(ctx):
await ctx.send(random.choice(topic))
``` I am trying to do as the bot @lament depot do here
but it's not working like I want to get a random topic from a list called topic
how to add an embed image
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
👍
Anyone?
Everything looks neat and clean
Name the list topics instead of topic. It's trying to get a random item from your function topic.
something like this
your_embed_name.set_image(url='image_link')
oh sorry
!e
import random
list = [1, 2]
print(random.choice(list))
Did you read what I said?
You said it is thinking it's a function
how to set color to embed
But I didn't understood
Can you tell me what should I do
embed = discord.Embed(
title='Title',
descriptoin='This is a description',
colour=discord.Colour.green() # < --- or another colour
)
for example
So how to name it
Just add a"s".
where
amm how to set using a color code

where s
color=your color code
👍
I am new to bot dev
#fffff ❌
0xfffff ✅
naming a variable isn’t exclusive to bot dev
What is the coding for my discord bot to type?
It's been a long time so I dont remember
!d discord.ext.commands.Context.typing
async with typing()```
Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
Note
This is both a regular context manager and an async context manager. This means that both `with` and `async with` work with this.
Example Usage...
what now?
amm error when i add img
I dont remember this
then define embed
❔
your_embed_name.set_image(url='image_link')
OOO KKK GOTIT
Now i need the coding that links my discord bot to aternos.
does anyone know the coding that links a discord bot to aternos?
Hey @limber mountain!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
https://paste.pythondiscord.com/uwupexaluc.sql what is wrong
This is the coding I have so far:
@bot.command(pass_context=True)
async def ping(ctx):
channel = bot.get_channel(893773954332897290)
await channel.send```
There's nothing after the send because I want it to send a message when my aternos mc server is online
pls tell hate this server
await channel.send("hello")
you always have to call the function, no matter what
and you can remove pass_context=True, since it does nothing
It's easy you can make one
You wanna send a message by bot?
@somber tree
@Bot.command()
AttributeError: 'Command' object has no attribute 'command'
{why is this wrong, it was working great, last night 🤔}
For some reason it sees Bot as a Command object
What do u have Bot defined as and where
Hey, some really weird bug appears to me
Code:
@bot.event
async def on_message(message):
embed = Embed()
channel = message.channel
if channel == chan(message.guild,"suggestions"):
await message.delete()
embed.title = "Suggestion"
embed.description = ''
embed.add_field(name="from:", value=f"{message.author.name} ({message.author.id})", inline=False)
embed.add_field(name="content", value=message.content, inline=False)
await channel.send(embed=embed)
Problem:
I am basically trying to resend the message as an embed, so suggestions are more detailed / cannot be deleted. It is sending the embed!... But it deletes it right away
Error:
Invalid Form Body
In embed.fields.1.value: This field is required
I have added the value kwarg!!!
Btw chan() gets the channel object, I coded that one myself lol
everywhere, it was great, last night.
It just means that the message.content is returning None
Oh- why that???
Meaning if the user uploads a file it won't work
I did not
Do u have intents
Yes
all()
?
Hmm then idk
hello
That tells me nothing, show where u defined your Bot
why does my bot fail to assign a role as soon as someone joins the server?
is it something with accepting the rules
Error?
no error
Code?
Do u have that popup thing where people have to confirm something first before joining the server (some discord feature)
it just doesn't show an error
I do
That could be the issue
Thats verification yer
does it not allow people to get a role?
I forgot what was its name in the lib tho
Perhaps, but ik there is something with it in the lib
Just forgot what it was called 😔
I guessed it cause I added a bot recently and the roles were added without an issue
wouldn've been better if I got an error
Then it's bc of that
@slate swan
Theres a second where I am able to see the embed and it shows the message.content in value
Ah now I see the issue
Hm?
You're deleting and sending the message in the same channel
Meaning that even if the bot sends a message, it will also count
Huh am I?
Where
Add ```py
if message.author.bot:
return
OHHHH
HAHAHAHAHAHA
I get it yer
Thanks lets see if it works
Yw
Yey
I’m sorry to interrupt anything if I do, since I started using uptimerobot, my bots start command stopped working and shows these errors
Why doesn't my code work...
@tasks.loop(seconds=1)
async def bot_run_time():
작동시간 = 0
if datetime.datetime.now().minute % 5 == 0 and datetime.datetime.now().second == 0:
a = time.strftime('%c', time.localtime(time.time()))
day = datetime.datetime.now().date()
try:
while True:
guilds = int(0)
presence = int(0)
for i in bot.guilds:
작동시간 = 작동시간 + 5
guilds = int(guilds + 1)
botruntimeembed = Embed(title="a", description=f'a', color=0xfff700, timestamp='now')
hook4.send(embed=botruntimeembed)
await asyncio.sleep(300)
except:
hook4.send("a")
Are you sure you're starting it
The error is self-explanatory and uptimerobot has no impact whatsoever
What exactly isn't working then
Ik but it keeps showing the errors even after I uninstalled uptimebot
I just said that uptimerobot has no impact whatsoever, the issue is your code
You forgot to put ctx somewhere in a command, read the error
I just want an Notice bot
I put the code back to where it was before installing the thing
U put it to repeat each 1s
How
what is hook4
@tasks.loop(minutes=5)
I made an hook with dhook
whats that
Dpy already has webhook support
Thanks for your help.
How do I work selenium in relp it?
I mean how to connect with bot...
use cogs
Use cogs
ooooooookk
The code was revised back to the version where it last worked, but here’s the main.py code.
Yes!
Read the error
- You're missing
ctx. - You're putting the wrong params
bruh
no spoonfeed
-_-
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Yes
we can help but not giving all the code
learn python then discord.py, don't start with dpy first
Whats the error?
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
Stop pasting your bot token
how do i make variables for custom emojis on discord.py?
you wanna store emoji's in a variable?
it'll be "invalid synxtax"
that's valid syntax
i want to create a config file for it, for example instead of typing <:danger:891768639836024852 > in every cmd i can just do config.tick for example
it's invalid
idk how to explain it very well
Examples...
make a json file
look at the message i sent above that...
and use a class
ive done that
the class would load the json file and then set the attributes
I want to use multiple COGs/Folders. Can I still use this or do I need to change the last line?
@bot.event
async def on_ready():
for cog in os.listdir(r"COGs"):
if cog.endswith(".py"):
try:
cog = f"COGs.{cog.replace('.py', '')}"
bot.load_extension(cog)
except Exception as e:
print(f"{cog} is failed to load:")
raise e
print(f"Logged in as {bot.user}")
why'd u remove the comments lol anyways yes you can still use that
How about the login part
IDK, to clean it up
use self?
ye
that will raise an error if on_ready is called again
you cant do that?
I want to have multiple folders
?
just load them ig
Yeaaa, How?
wym how
you dont need an event for loading cogs
What should I do?
do what?
Like I want to have multiple folders of COGs. That code wont work what should I use ?
multiple cog folders?
hey can someone help?
Yes
I want to name the folders like Commands, Rooms, Utilities
... and more
just load them like you loaded the other folders??
I dont load other folders
in an embed say if i want to use a custom emoji, i do description= 'hello world' how do i use a custom emoji because when i do description= 'config.tick hello' it dosent work
That's why I need help
meaning?
.
u said u wanted multiple cog folders?
bruh
its just a matter of changing names
can someone help me pls
...
for cog in os.listdir(r"COGs"):
if cog.endswith(".py"):
try:
cog = f"COGs.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"COGs_two"):
if cog.endswith(".py"):
try:
cog = f"COGs_two.{cog.replace('.py', '')}"
bot.load_extension(cog)
just put that in the on ready??
why?
wdym why
it can be called twice
what
what what
that will raise an error if on_ready is called again
this
u said it cant be called twice?
why are you loading cogs on an event?
where?
doesnt really matter
thats the same meaning innit
on_ready gets called multiply times
we dont question their code just leave it be?
it does matter. Do not load cogs on an on_event.
what?
?
?
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
That was your code and what you said?
this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
what code
just load the cogs else where?
stop making a big fuss out of small things lol
dude what
we just told you that on_ready can be called twice
and you misunderstood basic english
I'm not american?
nor am i
doesn't seem we were making a fuss, we tried correcting your code and you denied it, not accepting it?
anyways
nope
Heyy
do i really need to help you with that lol
Ye
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
It is what it is
can u show full code?
so that we can find where ur indentation error starts
for cog in os.listdir(r"Admin"):
if cog.endswith(".py"):
try:
cog = f"Admin.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"Embeds"):
if cog.endswith(".py"):
try:
cog = f"Embeds.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"General"):
if cog.endswith(".py"):
try:
cog = f"General.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"Misc"):
if cog.endswith(".py"):
try:
cog = f"Misc.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"Room"):
if cog.endswith(".py"):
try:
cog = f"Room.{cog.replace('.py', '')}"
bot.load_extension(cog)
not this full
?
import discord
import os
from discord import member
from discord.ext import commands
from datetime import datetime
from keep_alive import keep_alive
bot = commands.Bot(command_prefix="??", activity=discord.Activity(name="The Timelines", type=discord.ActivityType.watching), help_command=None, case_insensitive=True)
bot.launch_time = datetime.utcnow()
for cog in os.listdir(r"Admin"):
if cog.endswith(".py"):
try:
cog = f"Admin.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"Embeds"):
if cog.endswith(".py"):
try:
cog = f"Embeds.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"General"):
if cog.endswith(".py"):
try:
cog = f"General.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"Misc"):
if cog.endswith(".py"):
try:
cog = f"Misc.{cog.replace('.py', '')}"
bot.load_extension(cog)
for cog in os.listdir(r"Room"):
if cog.endswith(".py"):
try:
cog = f"Room.{cog.replace('.py', '')}"
bot.load_extension(cog)
keep_alive()
bot.run(os.getenv('TOKEN'))
This
This is the prefect example why you should not loop over your dir
here down its correct but somewhere in top the indentation error exists
wait what
What's happening
!e
import maths
print (maths.pow(2,10))
how do i use custom emojis inside an embed?
nothing nvm
just check top
What do I do?
.
check top lines of code
My code
ㅠㅠㅠㅠㅠㅠ
mmm
Use the code of it
what if i want to use config.(the emoji name)
here is a shorter one anyways ```py
import discord
import os
from discord import member
from discord.ext import commands
from datetime import datetime
from keep_alive import keep_alive
bot = commands.Bot(command_prefix="??", activity=discord.Activity(name="The Timelines", type=discord.ActivityType.watching), help_command=None, case_insensitive=True)
bot.launch_time = datetime.utcnow()
for f in [r"Admin", r"Embeds", r"General", r"Misc", r"Room"]:
for cog in os.listdir(f):
try:
cog = f"Admin.{cog.replace('.py', '')}"
bot.load_extension(cog)
except(Exception) as e:
print(e)
keep_alive()
bot.run(os.getenv('TOKEN'))
emoji=bot.get_emoji(emoji_id)
await ctx.send(f"{emoji}")
id !!
cog = f"Admin.{cog.replace('.py', '')}" Is this right?
async def embed(ctx):
embed = discord.Embed(
title = 'test',
description = 'config.tick test',
color = config.color
)
embed.set_footer(text='testing')```
i cant use config.(emojiname) inside description
@slate swan
oh ty, should i add that to my main file?
then
[-3] should also do the trick
[:-3]
@bot.command()
async def embed(ctx):
emoji=bot.get_emoji(emoji_id)
embed = discord.Embed(
title = 'test',
description = f'config.tick test {emoji} ',
color = config.color
)
embed.set_footer(text='testing')
await ctx.send(embed=embed)
@slate swan
:-3

ohhh okay
tysm
ping me if it works
in the {emoji} part should i add emoji name or id?
nono in
does anyone know how can you recreate UnbelievaBoat's "suggest" command?, i don't know how is it able to send a message with user's avatar
in emoji_id put that ID
@slate swan
ohh ok
any picture?
Like user avatar in the embed?
async def testembed(ctx):
emoji=bot.get_emoji(893824092816441354)
embed = discord.Embed(
title = 'test',
description = f'test {emoji} ',
color = config.color
)
? like that
yea
Fetch the channel > Embed the message > Send it
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||https://khadz.fuckedyourmom.today/
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
it says that
like this:
emoji is None
means bot doesnt have access to get that emoji
how do i give access to get the emoji?
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
Im pretty sure emoji id doesnt look like that but idk
u can only get emojis from ur own bot servers
not from other servers @slate swan
ye its from my server though
yeah, but how can you send a message with that avatar
hmm does the bot have access? @slate swan
yep
ctx.author.avatar_url or .url
send the url
can u use that emoji here @slate swan

yea
ctx.channel.send or ctx.send
that's a way to get user's avatar, not to send a message with it
yup
!d discord.Embed.set_author