#discord-bots
1 messages · Page 440 of 1
for guild in bot.guilds:
for channel in guild:
import discord
from discord.ext import commands
import json
import os
client = commands.Bot(command_prefix = "=")
@client.event
async def on_ready():
print("Ready!")
@client.command(pass_context=True)
async def register(ctx, member: discord.Member, *, nick):
if member.id == ctx.author.id:
await member.edit(nick='[0] ' + nick)
await ctx.send(f'You have registered as {member.mention} ')
#how to add roles?
role = discord.utils.get(client.get_guild(ctx.guild.id).roles, id = 882783428406284308)
await member.add_roles(role)
if member.id != ctx.author.id:
await ctx.send(f' Only register yourself!')
@client.command(pass_context=True)
async def ping_4v4(ctx, user: discord.Member):
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
if role in user.roles:
#if user has 4v4 host role, send embed
await ctx.send(f" 4v4 ping hehe ")
else:
await ctx.send(f" You don't have perms! ")
client.run(os.getenv("token"))
whats wrong with this code
afkaik guilds don't have .send method
there's like a rule for that
you have to tell the error too
@clever wind it's like a rule to not just ask what's wrong
yeah im gonna send that
There is no way he coded that
We need more information to help out.
msg was too long
just send the main error line
Ignoring exception in command register:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 15, in register
await member.edit(nick='[0] ' + nick)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 681, in edit
await http.edit_member(guild_id, self.id, reason=reason, **payload)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
😭
just read the error
your bot don't got perms
You don’t know what the error is but u can code that?
IM DINE
OH MY GOD
lol
Please read what it says.
😭😭
goddammit didnt see that
What does it say @hallow wigeon
might be most simple error to fix besides indent nd unindent
not a trick question
Missing Permissions
I mean, it's not that hard to code.
also im learning man lol chill its a combination of stackoverflow and tutorials
Think about how to fix a bot that is missing perms.
What?
your bot possibly doesn't have admin 😶🌫️😶🌫️
I was telling him to read the error
Nice
You replied to the wrong person, lmao.
Oops
lol
8
No
Give it the perms it needs, not admin.
Sussy backa
yea for test server give it admin
yes?
i'd rather add it with admin then have to test every cmd to see what permissions i have to give it
How can we help?
nvm i jus remember yeww can choice in dev portal
this won't work
It will loop.
it does work
what do you want
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
^
@slate swan what are you trying to do?
i asked if he wanted a certain channel or to send to a user he said any channels
in one channel?
.
you must define the channels first
you can make a list, you can select a channel using string like (general,welcome etc)
I mean you can choose a random channel from guild.channels
i do not code anymore soo
that's so ughhh
guild.channels[0]
or that
many ways
I'd say get the first channel that's a text channel.
have different checks
That's why I said add a try expect
you can do like, if no general found, search for chat, if chat not found rest
Some servers has special fonts for chat or general.
for them you can have a check to send to random or 1st channel
just create a channel for it .. but when i do that i have the problem of it cuz when it creates the channel for other servers it sends to them also
POV: you have 300 indents cuz you searched for every channel with ever font.
POV, you think smart and put all the check strings in a list, then loop through that list to check
and break if correct one found
@bot.command()
async def urban(ctx, *, search_terms : str):
"""Urban Dictionary search"""
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
try:
async with aiohttp.get(search) as r:
result = await r.json()
if result["list"] != []:
definition = result['list'][0]['definition']
example = result['list'][0]['example']
await bot.say("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
else:
await bot.say("Your search terms gave no results.")
except:
await bot.say("Error.")``` could someone help me fix this? im new with apis and im experimenting with this, im not using any cogs either just as a note
Thats is a very good idea
Didn’t think of that at all. Fair play

?
whats the error
@slate swan Here I made one rq and this works:
@client.event
async def on_guild_join(guild):
for channel in guild.channels:
if channel.permissions_for(guild.me).send_messages:
break
await channel.send("etc")```
async with aiohttp.get(search) as r:
AttributeError: module 'aiohttp' has no attribute 'get'
you need a ClientSession
Use requests?
!d aiohttp.ClientSession
class aiohttp.ClientSession(*, connector=None, loop=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, version=aiohttp.HttpVersion11, ...)```
The class for creating client sessions and making requests.
Hmmm, await bot.say?
that is blocking
Instead of this, I would send the messgae in the first channel in the guild, most likely it will be welcome, if rules is in the channel name then just return
Fair
should i change that? cuz thats another error
then do yourSesName.get
messgae
i know, but if they want to add additional checks like general 1st priority etc
so async with yourSesName.get(search) as r:?
if I made a bot, i wouldn't even add that feature
Yes, it's supposed to be ctx.send the way you're doing is old.
replace yourSesName with what you named your session
Same lmao, no purpose of adding it
yea
elaborate on session, im a bit rusty
import aiohttp
ses = aiohttp.ClientSession()
async with ses.get("url") as res:
# handle res
like here I named my session ses, so I did ses.get
I usually see a ClientSession as a browser
lol
Haha
There is going to be a error.
Change client to bot
Ahhh, okay.
Just making sure there is no errors.
add the check isinstance(channel, discord.TextChannel)
I think you can do if channel.permissions_for(guild.me).send_messages and isinstance(channel, discord.TextChannel):
@client.event
async def on_guild_join(guild):
for channel in guild.channels:
if channel.permissions_for(guild.me).send_messages and isinstance(channel, discord.TextChannel):
break
await channel.send("etc")
Yeah
indents are messed up in discord
So is discord.py gone
yeah there are forks though
So code doesn’t work
one of the famous forks is pycord
copy code and update
Heard about hikari
Oh so basically the code of discord.py won’t work
it will
but won't get updates
so like if you are making a new project, look for a fork
don't use dpy
Oh hmm ok so py cord where are the docs
its I think .gg/pycord
we sent the updated if condition..
even after that not working
sus
the channel.send needs to be where break is and you should get rid of the break
yea instead of break, have the send line
K thx I’ll uh Check it out gtg
kk
Hmmm, you don’t need intents right?
not indents,
Intents
What was the error?
hmm
aslong as it works
stops the for loop
i believe if all channels haev the permission it will send to all of them
since it's still in the for loop
^
@bot.command()
async def urban(ctx, *, search_terms : str):
"""Urban Dictionary search"""
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
try:
async with aiohttp.get(search) as r:
result = await r.json()
if result["list"] != []:
definition = result['list'][0]['definition']
example = result['list'][0]['example']
await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
else:
await ctx.send("Your search terms gave no results.")
except:
await ctx.send("Error.")```
any advice? theres an error on the aiohttp.get area im not sure what the error is exactly because of the handler at the end
Just delete the try-except then and see the error you are suppressing
@bot.command()
async def urban(ctx, *, search_terms : str):
"""Urban Dictionary search"""
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
async with aiohttp.get(search) as r:
result = await r.json()
if result["list"] != []:
definition = result['list'][0]['definition']
example = result['list'][0]['example']
await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
else:
await ctx.send("Your search terms gave no results.")```
like that?
edited, better?
You didn't dedent it
Do what sasuke said, break it after you sent the message.
dedent not indent which is what you just did
@bot.command()
async def urban(ctx, *, search_terms : str):
"""Urban Dictionary search"""
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
async with aiohttp.get(search) as r:
result = await r.json()
if result["list"] != []:
definition = result['list'][0]['definition']
example = result['list'][0]['example']
await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
else:
await ctx.send("Your search terms gave no results.")```
Still not dedented, it should be at the same level
lmfao
i havnt done this in years 😭
Now it isn't indented correctly
Yeah
The stuff inside of the context manager needs indentation
indent it
it should be at the same indent at await
if you don’t, it’s not gonna be in the if statement
ok so the conext manager is the "await bit", correct?
yes
@bot.command()
async def urban(ctx, *, search_terms : str):
"""Urban Dictionary search"""
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
async with aiohttp.get(search) as r:
result = await r.json()
if result["list"] != []:
definition = result['list'][0]['definition']
example = result['list'][0]['example']
await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
else:
await ctx.send("Your search terms gave no results.")```
better?
No you indented the wrong part
💀
@bot.command()
async def urban(ctx, *, search_terms : str):
"""Urban Dictionary search"""
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
async with aiohttp.get(search) as r:
result = await r.json()
if result["list"] != []:
definition = result['list'][0]['definition']
example = result['list'][0]['example']
await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
else:
await ctx.send("Your search terms gave no results.")```
better?
Yes
ily2 man
so this is the final product and it should work right
No it shouldn't as you said there was an error being suppressed
No it will send the error
This only shows the error
Then send the error so we do less work finding out what's wrong
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'aiohttp' has no attribute 'get'
get is a method of your ClientSession instance idk how I didn't notice that earlier
whats that mean exactly
Look at aiohttp docs, see this example on how to properly use it here
The relevant part is where the context manager starts
You don't need another async function as this is already in one
so what do you recommend i put down
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.urbandictionary.com/v0/define?term=') as resp:
print(resp.status)
print(await resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())```
like that?
Read
async with session.get('https://api.urbandictionary.com/v0/define?term=') as resp:
print(resp.status)
print(await resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())```
wht rlly?
The loop parts get rid of, and change the url to your url
How to stop playing audio with ffmpeg
Keyword of what I said earlier, “example” use it as a reference idk why you are copy and pasting it
You literally had most of this code already just needed to swap a few parts out by referencing the example
@client.event
async def on_member_join(member):
guild = client.get_guild(870969337945669722)
channel = client.get_channel(870969338235084841)
await channel.send(f' Welcome to Hive 4v4s, {member.mention}! Have fun!' )
nvm the guild cuz ill use it later but it doesnt seems to work with no errors
Dam nice
Nice
i want to buy a 5 dollar vps. How can i make the most out of it?
Idk
so that i use my free credit and all
come on.......
5 dollars is to much
wdym?
but on 5 dollars i cld run 2 bots right
so?
ok... im taking 5 anyways. My question is with the amount of credits i have, how can i maximise it
If you use dbs then get the extra features
dbs?
Like backup and stuff like that
Ye
i just want to get as much time as possible
i am a student, i can not pay for many months
I'm using discord.py, I need help with something. I'm trying to make it so when a user runs a command, it gives them a prompt and then waits for more input. How do I achieve this without having to use if statements to determine if they used a command previously
nvrmind
ok
how can i stop ffmpeg playing audio?
and how to give an error if it is already playing
Is it true discord takes 2 hours to register slash commands?
hey friends
I need help with this
if i want something to have 2 trigger words
would i just use "or"
use aliases
@commands.command(aliases=['leave', 'disconnect'])
async def shoo(self,ctx):```
this is what i had it as
but it kept triggering for every word instead of ch 4 and chapter 3
ok
elif isinstance(error, discord.errors.ClientException):
print("1")
await ctx.send(embed=discord.Embed("Sorry im already playing audio. Do !stop to stop it",color=discord.Color.random()))```
This should handle it if it is already playing audio right?
@client.event
async def on_member_join(member):
channel = discord.utils.get (member.guild.channel, name='welcome')
await channel.send(f' Welcome to the server, {member.mention}')
this doesn't work
does it have intents?
try:
rpl = await client.wait_for("message", timeout = 3.0, check=None)
print(rpl.content)
except TimeoutError:
print("what")
hold on thats super messy
try:
rpl = await client.wait_for("message", timeout = 3.0, check=None)
print(rpl.content)
except TimeoutError:
print("what")
ok so, does anyone know why when it's timing out, it still gives me an error rather than catching the exception
It still gives me TimeoutError
does it need to?
i feel like im trying to code this in py before rewrite maybe thats why its not working
change it to
except asyncio.TimeoutError:
import asyncio
you forgot a closing parentheses in a line above
did you put bot.event?
Most likely
it worked, thank you
@slate swan check to make sure you didn't forget a closing parentheses in any lines above, this is the most common cause for an error like this
yes
There should be a timer thingy, check the reference:
how do i add an image to this it keep giving error when i try
lol
Check the URL, make sure there's no spaces or typos
Im too lazy to read that entire thing lmao
could
thumbnail= 'https://media.discordapp.net/attachments/867833997728022599/882442193669849088/ezgif-6-0daf8e1e9fd6.gif'```
@slate swan
ok quick question tho, this is a bit off track. Why do python devs have a bad habit of using single quotes to encase strings lmao
quick follow-up question: why is it a bad habit
Hey @slate swan!
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:
Because python is one of the only languages where it is acceptable to use single quotes for a string. In other programming languages it's reserved for characters, so it's generally good practice to always use double quotes
what about shells, where both are acceptable but with slightly different interpretations?
python is also one of the only languages where indenting matters
true lmao
but indenting is not therefore "bad practice"
i dunno for me it's just "a thing about python" that's kind of a weird quirk
I'll give you "Weird Quirk"
lmao
here good?
code as an image is pretty inconvenient
do discord servers have unique IDs so I can create a web server and store bot settings differently for multiple discord servers
ahh ok
like i have a bot that's on two servers and it very much needs to know guild ID because if it wakes up and has to send a message "channel ID" is not enough
gotta know both
especially if it's looking up the channel by name
turns out there are a lot of "#general"s out there
yes lmao
also like, makes sense when you think of "big bots"
like there's a github bot out there, how many servers have installed that one
it's a large number
my stuff is for one or maybe two servers but
maybe one day i'll be famous
@bot.command()
async def testurban(ctx):
search_terms = search_terms.split(" ")
search_terms = "+".join(search_terms)
async with aiohttp.ClientSession() as session:
request = await session.get('http://api.urbandictionary.com/v0/define?term=' + search_terms)
catjson = await request.json()
embed = discord.Embed(title="{search_terms}", color=0xf6dbd8)
embed.add_field(name=f"Definition" + catjson['definition'])
embed.add_field(name=f"Upvotes:", value=f":green_circle: " + catjson['thumbs_up'])
embed.add_field(name=f"Downvotes:", value=f":red_circle: " + catjson['thumbs_down'])
await ctx.send(embed=embed)``` not sure where i went wrong
what's the error?
just a formatting opinion, not a habit
its on "search_terms.split(" ")
no
Where have you defined search_terms?
ill see if i even did that give me a min
Is it a discord TOS violation if I make it to where any server owner who has my bot has access to see when a user has been banned from other servers with the same bot and why
I feel like it's honestly just useful. Oh you wanna be mod, huh? lemme just pull up your collective record from servers who also use this bot
lmao
@slate swan I don't really think it will be a ToS violation but imho, it can be sort of a privacy thing cz I don't really think any server would want to leak it's ban list to other server owners...
It's a feature. You can choose what info to upload
This way, raids can easily happen. Seeing the raiders are unbanned, chances of raids are increased imho
Well I appreciate your honest feedback, man! I just finished learning python, so now is the point where I'm actually doing stuff
Ah, cool. Best of Luck with all that!
BTW @visual island disnake is in alpha testing now, in case you will want to install it from pip
@maiden fable you woke up at 10 again?
Kylee comes here before I could ping
Eh, my cook started banging hard on the door, so I had to wake up at 8 (I slept at fucking 2:30 AM)
It's not against ToS but it kills privacy of users. Unless it's very important, you shouldn't do it
hmm
wait
!pypi disnake

I do have a really good idea though, basically it's a bot you can DM and set up a profile with stuff like your age range, interests and such and look for a random person to chat with
also it's dislash.py
Hmm, what about catfishing? Ever thought of that haha
lmao ikk. But I just wanna make something coool
Though it's a good idea
Oh I know! I'll make a program that shows me the location of all working mcdonalds ice cream machine- oh wait, the simpsons already did it bro
😂
Make a discord bot Work at McDonalds
Lmao
You might find this super cringey, but I started programming because of a certain 12 year old crackhead.. if you get the reference, we are now friends
Haha
yay
For me, I always had an interest in programming. I wrote my first program at the age of 12?
Yay the bug has been fixed. Install from the master branch
disnake stores test guild
Lol
you install dpy from pip, but for bug fixes, you install from master branch
Or u can monkeypatch it if u want. It would be faster
for bug fixes, you install from master branch
quote this
Lmao u just did it
oh yea I just did it
Install stable -> has bugs
Install from master -> stable
only disnake
Eh
lmfao
I don't really think there is a reason to publish another reason to fix only one bug
I never said master was stable
it just has one or two extra bug fixes
Also, it's in Alpha testing, so you can't blame anyone haha
What's a good format for a file to store data such as tables locally on my laptop for use of the discord server
JSON
Don't kill me
Anyways, use the discord message as db
That's what I do hehe
😎
One fork changed the discord.gg thing to pda.gg lol
I was gonna try learning SQL but figured it's not worth the hassle for a simple discord bot
at least not rn
We just did Ctrl+D to exchange discord with disnake
Wanna see a pic?
Sure
bro wtf
(:
We had to rename the package disnake. What would have been a better way 
I mean your database
Ah
It might be first time I'm recommending someone to use json, please stop this 
Well, it's abandoned now. It's a private bot anyways
I once considered using the google sheets API for a database
I have shown that pic about 61613161870431346491048463161 times before (and yea, it isn't a random number, totally not)
ok so quick question:
?
I wanna store python arrays outside of the script, on like a txt file or something, can I do that
Mhm
Akshu will kill me if I say that u can use JSON to store list
lmao
I'm already super confused about the discord message thingy
Exactly, but you can still use json with some efficiency tricks
He's already in shock that how can I use messages as db lmao
I'm in shock on how you even thought about it and went through using discord channel as a database
I won't wonder if he even uses pen-paper now 
I was too lazy to learn a db and didn't want an external JSON file cz its easy for me to overwrite it

Hmm I don't know I think I would prefer json over what you did since it would be easier to interface, etc
And you know, imagine if you had a dynamic prefix and the message wasn't cached
There goes all the commands
It's not good to use json in bot but if you still want to do that, you can just create a timed task to asynchronously open the file every few minutes and dump the cache
im making my own file type because I am extra lmao
Why tho?
You don't really need to dump the cache
You can read the JSON when constructing the bot, cache every data. On commands that update, update the cache
Then in your close method write to the database
Eh, it's a private bot anyways. I don't want to get ratelimited by using it in a big bot
On the off-chance my bot were to blow up, so would my computer
I mean by storing in json instead of a database
Yea, which is what I was talking about
They don't have any database, just json.. and they have no idea when their bot is gonna shut down next (a typical replit hosting)
If that is the case, use aiofiles and only open the file in the same method that writes any new data
I wanna get a real web server, but it scares me after my friend telling me his heats up his entire room to 104 degrees F
Yeah
how do i set local image in embed
!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.
Ok?
it was after my nitro expired so I got randomized again
I was just saying it was lucky to have 2 and 2
yeah ik lol
just keep making new ones til you get a good number idk
Indeed
But instead, discord wants to make slash commands popular by making messages intent a privileged intent
Great, add another useless nitro feature rather then fix things for developers
just out of curiosity, does anyone use pycord instead of discord.py
pycord is kind of trash
Idk
I'm gonna make a server called "EA" and you have to buy credits for sending messages lmao
Totally EA
is there any way a role can edit the role above it?
no
that makes my code a lot easier
is there a library I can use to allow me to create folders on my computer with python
nvrmind, just found it
But it will throw an error
Missing Permission or something
yeah I know
Ah cool
god my code is getting increasingly messy and i dont know how to clean it
oh nice didn't know that was a thing
!pypi flake8
when using the on_guild_join event, how do I find the channel the bot joined in on
Wym...?
or like, uhhh
I wanna make it to where it will send a message when it joins a server, how do I find the best channel for that
oml lmao
I helped someone out with the same problem, hold on.
@client.event
async def on_guild_join(guild):
for channel in guild.channels:
if channel.permissions_for(guild.me).send_messages and isinstance(channel, discord.TextChannel):
break
await channel.send("Thanks for inviting me!")
This will find the first channel the bot is allowed to send messages in.
Ah, so u mean, like Groovy does it?
Yeah i’m pretty sure that’s what he means.
Ah, I misunderstood then
there's this one
Thank you
!d discord.Guild.system_channel
system_channel```
Returns the guild’s channel used for system messages.
If no channel is set, then this returns `None`.
Can we kick more than 1 person at a time?
@commands.command()
async def help(self, ctx):
embed=discord.Embed('Full Help Page', description='hi')
embed.add_field(name='Commands:', value='Hug: `hugs the user`\nBonk: `bonks the user`\nKiss: `kisses the user`\nSpank: `spanks the user`\nSlap: `slaps the user`')
await ctx.send(embed=embed)
``` why isnt this working
Maybe title is a keyword only argument
oh I didn't see it my bad
how can i host my discord py bot? on vultr
"rpl = wait_for("message", check = None, Timeout = 60.0)", telling me wait_for is not a function
it's bot.wait_for
or whatever you defined commands.Bot as
"commands" not found
Am I just dumb, ffs
bruh okay
where's your bot constructor?
Oh it's Client.wait_for
yes, so you defined Client as commands.bot
constructor for what lmao
.. didn't you do something = commands.Bot(...)?
Or are you using discord Client
No, I just have client = discord.Client() lmao
I don't have a var for bot
@bot.command(pass_context=True)
async def hand(ctx):
variable = [
"1",
"2"]
embed = discord.Embed(color=0xf6dbd8)
embed.set_image(url=variable)
await ctx.send(embed=embed)``` command dosnt work, any ideas? the variables are supposed to be urls but i removed the urls to prevent spam
okay, hmm
try client.wait_for
Just did, figured it out
thx tho
you want it to put multiple urls?
i want it to randomly make an embed of an image
try another variable random.choice(variable) and set this to the url
@bot.command(pass_context=True)
async def hand(ctx):
variable = [
"1",
"2"]
embed = discord.Embed(color=0xf6dbd8)
embed.set_image(url=random.choice(variable))
await ctx.send(embed=embed)```
helphhhhh
like that?
yeah try
!d discord.ext.commands.Bot.guilds
guilds```
The guilds that the connected client is a member of.
bot.guilds not servers
does anyone knows about Py-cord
i have a doubt how can i make a discord bot send a .txt
Mhm
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
ok thanku
umm is this correct ? if message.content.startswith('!docEntity'): await message.channel.send.discord.File(fp, filename=Entitydoc*, spoiler=False)
anyone ?
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
Use the file kwarg
ok
thanku
Can I see where u have defined launch_time?
OHHH my bad sorry
!d discord.Member.mention
mention```
Returns a string that allows you to mention the member.
@slate swan ^
to mention a user invoking the command,
ctx.author.mention
hey i'm using replit to make a music bot, do i have to install the ffmpeg software on my system or can i just import the required libraries ?
hi, so in dpy you can do like class MyCog(commands.Cog, name="MyCog") right? how did they implement it? i've tried using __init_subclass__ and i think it doesn't work quite well, and raise an error: TypeError: __init_subclass__() takes no keyword arguments
class EnumMeta(type):
"""This metaclass makes a class iterable (iterate through class vars)."""
def __iter__(self):
yield from [i for i in self.__dict__.values() if str(i).isdigit()]
def __init_subclass__(mcs, **kwargs):
mcs.__type__ = kwargs.pop("type")
class Channels(metaclass=EnumMeta, type="hi"):
...
```code btw *changed a bit
i am not able to figure it out
where to put the command
why not use commands
you are using a on_message event to check for commands
when you can just make commands yourslelf
already wrote 6000 lines of code in this so
i had a problem
lolwhile learning
all your bot features are with on_message event?
bruh
600 lines now
well, that is a bad practice
@bot.event
async def on_message(message):
mention = f'<@!{bot.user.id}>'
if mention in message.content:
embed=discord.Embed(title=f"Server Prefix", description=f"My prefix in this server is `{prefix}`", color=0x008000)
await message.channel.send(embed=embed)
await bot.process_commands(message) ```
when i add these the prefix is not working when i do `.help` it is not coming but when i remove this it is coming is there any problem with this?
ye ik
how would you even have args for commands lol
see
what is the error
or what do you want?
You want to mention who used the message? do message.author.mention
I would suggest you use commands instead of the on_message event, but it seems you've gone far already
but you can still do it
no error
i want to mention the person whu asked for it
Dpy uses metaclasses, instead of __init_subclass__
https://github.com/Rapptz/discord.py/blob/v1.x/discord/ext/commands/cog.py#L36-L147
Look at the __new__ method of CogMeta it will iterate over the attributes of the class and check if it is an instance of commands.Command if it is an instance of Command it gets appended to a list
hmm, i tried to use __init_subclass__ and got this warning, it works tho, i can access Channels._type
seeeeeeeee
@spring flax see
idk
Oh
i'll try using __new__
What are you trying to do @slate swan
i want to tag the user whu has asked for command
Try this:
k
await message.reply(embed=embed)```
maybe pycharm being strict
thnx it works
aah, it works, tyvm rush
https://sourceb.in/ev7wkk8vqx what is wrong in the levling system
- the users.json file is there
- it has {
} these things - still not working
4.pls tell
5.pls help
error https://sourceb.in/hujuR4uslF
no json
python only
ohk
!e ```py
class EnumMeta(type):
"""This metaclass makes a class iterable (iterate through class vars)."""
def new(cls, name, bases, attrs, **kwargs):
attrs['type'] = kwargs.get('type', None)
return super().new(cls, name, bases, attrs)
def __iter__(self):
yield from [i for i in self.__dict__.values() if str(i).isdigit()]
class Channels(metaclass=EnumMeta, type="hi"):
...
print(Channels.type)
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
hi
yeah it worked already
ty
so can you help
no me work on moderation not levelling yet
trying and learning
people can copy whole code
👍
@slate swan why no make commands and not on messages?
wait, why should i super() it?
super what?, the __new__?
yeah
yes
how
cause already wrote 600 lines of code
and I dont know how do i
Why though
wht i learnt from onlne as well as used my own knowledge
i need someone to help me edit
or else i will have to use on_messgae
on_message
@boreal ravine
__new__ must return the newly created class, type.__new__(cls, name, bases, attrs) returns the class according to the given attributes, because you are overriding the __new__ you need to return the newly created class
Anybody with experience of Discord Bot development?
I have Work for you!
oh, yeah the Channels._type returns None without it
wait
it still returns None
Edit what
How do you save a sent screenshot as a temp photo , like png
oh, my bad (i missed typed a thing)
i have only have one project which uses metaclasses
havent found a use for it other than that
but metaclasses are fun imo
can you help with moderation
pycharm sucks lol
i know dude it is the worse
guys can we do the module exports things in python can yall teach me
@visual island
@commands.has_permissions(kick_members=True)
async def kick(ctx, *, member:discord.User, reason="No reason provided"):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot kick yourself.")
if bot.role.position > member.top_role.position:
await ctx.send("You cannot do this action on this user due to role hierarchy.")
return
await ctx.guild.kick(member, reason=reason)
await ctx.send(f"Kicked **{member}**")
await member.send(f"You have been kicked from **{ctx.guild}** for Reason: {reason} Responsible Moderator: **{ctx.author}**")
return
whats wrong in this if i try to ban a member above bots role it is not send you cannot do this action due to role hierrachy
how do i get user's status? i mean i know how but i also have an emoji for each status, how do i send the emoji with their status name
can anyone recommend a good discord bot's code here?
the whole code
yeah wht u need
of course bruh
if ur bot has administator then also it will not do cause person above the role also has higher role so it does not work
uh sure
no spoonfeed
can u help
yes
yes DMs
me lol
just do member.status
it'll return a emoji if there is
str(member.status) returns without emoji
times mute
in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type set is not JSON serializable
``` what is wrong
guys how to set a role colour
!d discord.Role.color
color```
Returns the role color. An alias exists under `colour`.
role.edit
await edit(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
i read that as how to see a role color mb
How?
@client.event
async def on_member_update(member, after):
print(f'{member} has updated his account information!')
@client.event
async def on_user_update(member, after):
print(f'{member} has updated his account information!')
Yoo guys tryna use on_user_update and member update but how do I show what has updated?
like "Twisterzz#1446 has changed his Profile Picture"
How to do kick commend?
await member.kick()
i suggest using
async def on_member_update(before, after):
so it makes it easier to understand
if you want to add more code to that event
then when I print who updated their info it isnt defined
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
print(f'{member} has updated his account information!')
No
it now says member isnt defined
no, use before
yea
ahhh
before and after are member objcets
you can compare the before and the after
objects*
so before is the member's before data, after is the member's new data basically
example
if you want to look for nickname changes:
if before.display_name != after.display_name:
#code
Thank you
async def on_user_update(member, before, after): is this what I do for my async
no need member
but then it says it isnt defined
@proven elm
instead of using member, use before/after
before.display_name for example
ahh okay thank you
@client.event
async def on_member_update(before, after):
print(f'{before} has updated his account information!')
Example ^
show whole code
well guys he helped me a lot @spring flax by 2-3 days i think i will edit the code
thnx bros
👍
@boreal ravine he helped me

how do i fix this
wht u need to fix

!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3.10/library/datetime.html#strftime-strptime-behavior).
Hello guys
i am creating a bot in discord.py and i am doing a reaction role system, the code is right only that when the bot is online it does not send the message for the reaction role
Here the code:
@ client.event async def on_readyy (): channel = bot.get_channel ('872109565280387172') role = discord.utils.get (user.server.roles, name = "Bot tester") message = await bot.send_message (channel, "React to the message to verify yourself.") while True: reaction = await bot.wait_for_reaction (emoji = "✅", message = message) await bot.add_roles (reaction.message.author, role)
There's so many wrong things in your code
1st what's with all the spaces
2nd it's on_ready not on_readyy
3rd is your bot instance named client or bot? Don't use both, use the one that you have, if it's client then bot.get_channel will be client.get_channel
from PIL import ImageDraws
ImportError: cannot import name 'ImageDraws' from 'PIL' (/usr/local/lib/python3.8/dist-packages/PIL/__init__.py)
Is there any fork of discord.py that seems good enough to use it, or is to soon?
Help fix error
1 spaces creates discord, in the code there are no spaces
2 on_readyy I named it this way because I already have another one called on_ready
4th ids are ints not strings
It won't work
You can only have 1 on ready
If you want to have more use listeners
can u help me?
ooh true how did I not think about it ...
It's ImageDraw
Anyways 5th, there is no wait_for_reaction
It's wait_for
You are using client.event and you also have bot.get_channel.
Why both?
Successfully installed Pillow-8.3.1
root@Zeroandone:~/chad# python3 bot.py
Traceback (most recent call last):
File "bot.py", line 20, in <module>
from PIL import ImageDraws
ImportError: cannot import name 'ImageDraws' from 'PIL' (/usr/local/lib/python3.8/dist-packages/PIL/init.py)
root@Zeroandone:~/chad#
@slate swan i tried to put everything with client, but it doesn't send the message anyway
remove the "s"
its ImageDraw
U didn't change it
It's not ImageDraws
Trying to do unban commands but it only recognises users if their in the discord how do I make it understand their discord IDs?
.
Bc the whole code won't work anyways
why?
You didn't define user
alr got it
And all of the above that I mentioned
Also
but he does not say to define it. sorry for the ignorance how would I define the user?
Use discord.User
async def cmd (ctx,user:discord.User)
@slate swan
user = bot.get_user(userid)
thaanks
I've never used a vps but I'm pretty sure that's how it's supposed to work
Can i do embed with discord py?
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
Still I would recommend that you don't use reactions in on_ready as it won't work the way you probably intend it to
Using on_raw_reaction_add would be more fitting
@client.command()
async def unban(ctx, user):
await ctx.discord.unban(user)
await print({user}, "has been unbanned from the server")
'Context' object has no attribute 'discord'
Context.discord isnt a thing
Where you define your params, user: discord.User
ohhh ok
Help me pls
with?
Python-dotenv could not parse statement starting at line 2
Python-dotenv could not parse statement starting at line 4
Python-dotenv could not parse statement starting at line 2
Python-dotenv could not parse statement starting at line 4
your .env is probably not formatted correctly
it is
shld i..... send it?
alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU VWXYZ!@#$%&*()-_+="';:<>,.?{}[]"
and that's incorrectly formatted
.env doesn't have quote marks
for instance it would be
TOKEN=abcDEFghiJKLMop
CHANNELID=123435658487
ROLEID=38737187183
SECRET=sdkjakSDGKJASDHFfjiusd84hjsfndJKH
IP=123.456.789.1
@gloomy coral that's how env is formatted
Oh
damn
Guys
@valid niche
im using vultr, and when i close my putty session the bot goes offline! how can i fix?
Wut?
how to do tht
umm I need some help, I got this,
can someone explain whats the problem here?
this is for a music bot btw^
Hi guys, I created a role reaction system in discord.py, practically you create the embed with the reaction, but the click on the reaction does not give me the role. Can anyone help me?
The code here:
async def on_ready():
print('Bot online')
await client.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f'in {len(client.guilds)} servers | !aiuto for help | !invita for invite'))
@client.event
async def on_raw_reaction_add(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
await payload.member.add_roles(role)
@client.event
async def on_raw_reaction_remove(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
await client.get_guild(payload.guild_id).get_member(payload.user_id).remove_roles(role)
@client.command()
async def reactrole(ctx, emoji, role: discord.Role, *, message):
emb = discord.Embed(description=message)
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction(emoji)
with open('reactrole.json') as json_file:
data = json_load(json_file)
new_react_role = {
'role_name' :role.name,
'role_id' :role.id,
'emoji' :emoji,
'message_id' :msg.id
}
data.append(new_react_role)
with open('reactrole.json', 'w') as j:
json.dump(data,j, indent=4)
Install screen from your package manager, like apt install screen. Then do screen -S name (and replace name with whatever you want to name it) to make a new screen. In the screen start your bot. Then press ctrl + a ctrl + d to detach so it runs in the background. If you ever need to go back you can do screen -r name to go to the screen with that name. And when you want to close a screen go into the screen and type exit
You need to learn Python before making a music or any discord bot
uhh yea...
ok
but u a bit late lol
a am using pm2
ill go ask somewhere else sry..
guys please help
Stop using dpy as your first project and choose a simpler one, and you can ask general doubts in #python-discussion or #❓|how-to-get-help
Hi guys, I created a role reaction system in discord.py, practically you create the embed with the reaction, but the click on the reaction does not give me the role. Can anyone help me?
The code here:
async def on_ready():
print('Bot online')
await client.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f'in {len(client.guilds)} servers | !aiuto for help | !invita for invite'))
@client.event
async def on_raw_reaction_add(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
await payload.member.add_roles(role)
@client.event
async def on_raw_reaction_remove(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
await client.get_guild(payload.guild_id).get_member(payload.user_id).remove_roles(role)
@client.command()
async def reactrole(ctx, emoji, role: discord.Role, *, message):
emb = discord.Embed(description=message)
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction(emoji)
with open('reactrole.json') as json_file:
data = json_load(json_file)
new_react_role = {
'role_name' :role.name,
'role_id' :role.id,
'emoji' :emoji,
'message_id' :msg.id
}
data.append(new_react_role)
with open('reactrole.json', 'w') as j:
json.dump(data,j, indent=4)
@commands.command(aliases=['enc', 'script'])
async def encrypt(self,ctx, *, text_to_encrypt: str):
valid_reactions = [':trash:']
embed = discord.Embed(title="Encoding your message :zo_typing:",
description="This stays in between us. :wink:\n Keep this a secret. :zipper_mouth:")
embed.color = discord.Color.dark_blue()
embed.set_footer(text="You all saw NOTHING")
embed.add_field(name="Encrypted Text", value='`' + enc.encrypt_text(text_to_encrypt) + '`')
message = await ctx.send(embed=embed)
await message.add_reaction(':trash:')
def check(reaction, user):
return reaction.message == message and str(
reaction.emoji) == ':trash:' and user == ctx.author
await self.bot.wait_for('reaction_add', check=check)
await message.delete()```
why doesnt this delete the embed on reacting
guys..i am using matplot to save the plot and send it as an attachment..something weird is happening..plot of two successive commands is getting mixed
Looks like a question for #data-science-and-ml
how can i check if the author is in the same vc with the bot?
ctx.author.voice.channel
Yeah, I pay $80 for specs that you can get for $30. Unfortunately you have to pay full time on other vps's since there's a 90 day money back.
help lol?
how can i ignore deprecation warnings and attribute errors?
Wdym ignore
like not displaying it in the console
?
it tells this interaction failed
How can I make the bot edit the message
Hey @stray stump! 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!
lol
import discord
import time
TOKEN = ""
client = discord.Client()
@client.event
async def on_ready():
print("Logged in as {0.user}".format(client))
client.run(TOKEN)
@client.event
async def on_reply(message):
user_n = str(message.author).split("#")[0]
user_m = str(message.content)
channel = str(message.channel.name)
if message.author == client.user:
return
if user_m.lower() == "Hello":
await message.channel.send(f"Hello {user_n}, how's your day?")
return```
i removed token btw ^
can anyone help me with this?
How can I make the bot edit the message
?
And?
Show code
in dms?
!d discord.Message.edit
await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
No
why
fine
Noone cares
What lib are you using
wdum
this?
from discord_components import DiscordComponents, Button
Uh
import discord
import time
TOKEN = ""
client = discord.Client()
@client.event
async def on_ready():
print("Logged in as {0.user}".format(client))
client.run(TOKEN)
@client.event
async def on_reply(message):
user_n = str(message.author).split("#")[0]
user_m = str(message.content)
chann = str(message.channel)
if message.author == client.user:
return
if user_m.lower() == "Hello":
await chann.send(f"Hello {user_n}, how's your day?")
return```
it doesnt reply
Idk anything about discord components, ask it in their support server
bruh
why u runnning ur bot after the on_ready
not at the end of ur code
Using discord.Client() is the worst thing you can use.
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Start by reading that
!d discord.Message.edit
await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Thankss
hi guys how can i get all messages in channel ?
oh..
hello can someone help
With?
see #help-cookie
so right here, I add a reaction ✅ but I also want to see if a user reacted with it too, how can I do that?py @bot.command() async def test(ctx): embedVar = discord.Embed(description='Please wait for an admin', color=0xc754f) msg1 = await ctx.send(embed=embedVar) await msg1.add_reaction('\N{White Heavy Check Mark}')
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
there is an example for reactions
So my bad word filter keeps deleting anything even if it's not in the yeah.txt file. How can I fix it?
Code:
letters = ("à", "á", "â", "ä", "æ", "ã", "å", "ā")
with open("yeah.txt") as file:
test2 = file.read().split('\n')
@bot.listen("on_message")
async def on_message(message):
guild = message.guild
bypassedRole = discord.utils.get(guild.roles, name="Bypassed")
if bypassedRole in message.author.roles:
return
for word in test2:
regex_match_none = re.compile(fr"([{letters}]+{word})|({word}[{letters}]+)", re.IGNORECASE)
if regex_match_none.search(message.content) is None:
await message.delete()
embed = discord.Embed(title="Message Deleted", color=0xD708CC, description= f"{message.author.mention}, You're not allowed to say that.")
embed.timestamp = datetime.utcnow()
await message.channel.send(embed=embed)```
thanks man!!```py
@bot.command()
async def test(ctx):
await ctx.send('Send me that 👍 reaction, mate')
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '👍'
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.send('👎')
else:
await ctx.send('👍')``` this examples works but if I have the timeout as None, do I remove the except and else statements?
You can just not put it?
@bot.command()
async def test(ctx):
await ctx.send('Send me that 👍 reaction, mate')
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '👍'
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
await ctx.send('👎')```?
the indentation is wrong
and you cant have try alone
yes
help pls
edited it
@bot.command() async def invite(ctx): embed=discord.Embed(title="invite me", url="https://discord.com/api/oauth2/authorize?client_id=876383024089006100&permissions=8&scope=bot%20applications.commands", description="invite me to your server ", color=0x00e1ff) embed.set_author(name="bot") await ctx.send(embed=embed)
now its better right
File "main.py", line 130
await ctx.send(embed=embed)
^
SyntaxError: 'await' outside function
anyone help pls
you cant have await outside async functions
??
done
bro it was indentation problem
ok
i got this error now
File "main.py", line 129
embed.set_author(name="bot")
^
IndentationError: unindent does not match any outer indentation level
Send your code also
@raven peak
async def invite(ctx):
embed=discord.Embed(title="invite me", url="https://discord.com/api/oauth2/authorize?client_id=876383024089006100&permissions=8&scope=bot applications.commands", description="invite me to your server ", color=0x00e1ff)
embed.set_author(name="bot")
await ctx.send(embed=embed)
indent the last 2 lines
ty bro
👍
How do you mention a role? py await ctx.send(@hollow hound) doesnt workSyntaxError: invalid syntax
well its simple
u gotta put quotes lmao
await ctx.send("@hollow hound")
if its a valid role it shld work
Hi guys, I'm doing a reaction role system, the code doesn't give errors, the command exists, but if I call it it doesn't give me any answer
async def reactionrole (ctx):
if ctx.message.author.server_permissions.administrator:
testEmbed = discord.Embed (color = discord.Color.red ())
testEmbed.set_author (name = 'Test')
testEmbed.add_field (name = 'Test', value = 'Test')
msg = await client.send_message (ctx.message.channel, embed = testEmbed)
await bot.add_reaction (msg, emoji = ':white_check_mark:')
@ client.event
async def on_reaction_add (reaction, user):
Channel = client.get_channel ('872109565280387172')
if reaction.message.channel.id! = Channel:
return
if reaction.emoji == ":white_check_mark:":
Role = discord.utils.get (user.server.roles, name = "Bot tester")
await client.add_roles (user, Role)```
its a role id
there is a space between @ and client
yeah try it just put quotes
it is discord that shows it like this, in reality there is no space
i did, doesnt work, no errors or nothing it just does @the_id
@lament mesa
compare the emoji to the unicode
wdym?






