#discord-bots
1 messages · Page 542 of 1
you can set a profile to webhooks
theres literally a kwarg for that
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
nvm yeah it was a webhook. In mobile it looked like a profile but now that i'm on my pc, it definitely is a webhook
hm
music = discord.utils.get(client.voice_clients, guild=ctx.guild)
channel = ctx.author.voice.channel
if not music.is_connected():
await channel.connect()
``` Why does that not working? `Command raised an exception: AttributeError: 'NoneType' object has no attribute 'is_connected'`
what error consol also run ?
and i deployed
is the bot in the vc?
No, I want to check for it with that
Hey, what is the code to fetch a role in nextcord?
Why isn't this if statement working
async def dm(ctx):
for file in filenameArray:
file = file.replace(".png","")
if(ctx.author.id == file):
await ctx.author.send(url)
@boreal ravine
hm
!d discord.ext.commands.Bot.get_role same syntax
No documentation found for the requested symbol.
uh oh
hey i was making an economy bot and im pretty new to this so im learning and writing the code altogether, but it doesnt seem to work can someone help?
i mean sure
how do i use the pastebin thing
Hi, I was wondering if it's possible to purge messages just by id alone. I've been trying to rack my brain but nothing is coming up, does anyone have any idea?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Hello friends
Can you teach me how to write in color like this ?
Thanks 🌹
!code
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.
if ctx.author.voice:
music = discord.utils.get(client.voice_clients, guild=ctx.guild)
channel = ctx.author.voice.channel
# if not music.is_connected(): if ctx.guild.me.voice is None:
await channel.connect()
if ctx.author.voice.channel == ctx.guild.me.voice.channel:
if music.is_playing():
music.stop()
```Both ifs aren't working....
whats the error?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@umbral carbon put {} in the json file
i did
Thanks a lot 🌹
guys I got a sick idea for a game bot! not sure how long it'll take to make it but I think its worth making
what is it
if I reveal it, someone might copy 😢
its not exactly easy to just make it but someone good might be able to pull it off
im someone bad
lol
I mapped out whole process about how I would make it work
but I don't have time to make it happen soon 💀
BTW how do you guys increase the reach of your bot initially?
what if your friends don't own servers
your friends have friends
well honestly only 2 of my friends own servers that I know of
and I was the og owner of one of those
even if you get it into 1 big serveer
its pretty decent at 2.6k members rn
it might pop off
Hi, I was wondering if it's possible to purge messages just by id alone. I've been trying to rack my brain but nothing is coming up, does anyone have any idea?
wdym just by id?
is 2.6k big enough?
maybe
hmm
true
Like the discord id so the unique number linking to an account
tho I have no irl friends on discord who r active now. I will have to depend on online friends
so that only 1 person can run the command?
So I can purge the messages of that one specific person so like I want it to be like .purge id number and it'll purge all messages from that user
It's Oki and idk how to do that
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
help :(
I'm confused lmao
would be more helpful if you'd describe your error
hello i have a question do i can make a discord bot that can kick all ppl in the server ?
@slate swan this is the exact error
this didnt work?```
{
}
nope
await channel.purge(limit=amount, check=lambda m: m.author.id == user_id)
it deleted teh curly when i ran the command and idk if thats intentional
Oooo ty
or like if i get all the ppl ids i can store them in a notebad and he start kicking them
any help ?
a loop i guess
yes i think it might work if i use a loop
ok no after testing that it errors
run a for loop on a list of all members in the server but why do you want this 💀
tell me if you guys know anything
ooh oki
fixed it
tysm
!empty-json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
lemme see
💀
Lmao
lmAo
he shouldnt play with a developer
<@&831776746206265384>
what ?
@hollow mortar it wasn't a good idea to ask that here bro
you probably shouldn’t have pinged mods
nah im not asking about it lol
should've gone to google instead
it deleted the curly when i run teh command
it’s a better idea to dm modmail
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
define user
bro chill
you haven't defined user
stop mods or anything it was just a joke mnan
either works for me
got everything removed man chilllllllllll
i dont think it works
it does
i must be using it wrong
i didnt ask for a code here for that problem that guy just asked and i told him
show how you're using it
no
@client.command(aliases=['boosterlist'])
@commands.cooldown(4,15, commands.BucketType.guild)
async def boosters(ctx):
list = ctx.guild.premium_subscribers
boosters = ""
count = 0
if len(list) > 0:
for boosters in list:
boosters.name
count += 1
boosters += f"\n`{count}` {booster.name}#{booster.discriminator} `({booster.id})`"
for user in list:
embed = discord.Embed(title=f":boost: {ctx.guild.name}'s boosters" ,description=boosters ,color=0xd40000)
await ctx.send(embed=embed)
@potent jetty
wait nvm
lemme edit it
i did .clear id amount and the other way
you're trying to get a list of boosters and no. of boosters right?
Are you defining an object?
could also use enumerate
and in your code?
ok wait
@commands.command()
@commands.has_role('Mod')
async def clear(self, ctx, amount : int):
channel = ctx.channel
await channel.purge(limit=amount, check=lambda m: m.author.id == user_id)
Embed=discord.Embed(title=f":white_check_mark: | Deleted {amount} messages", color=0x228B22, timestamp=ctx.message.created_at)
await ctx.send(embed=Embed, delete_after=10)```
!codeblock
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.
Also keep in mind the person who made the tutorial you’re following, I’d say avoid them. They teach very bad habits like telling you to use json for persistent storage.
put your code in a codeblock
did it already
you don't have user_id
yeah i know, i'd be learning more myself i just wanted to try this out
@client.command(aliases=['boosterlist'])
@commands.cooldown(4,15, commands.BucketType.guild)
async def boosters(ctx):
booster_list = ctx.guild.premium_subscribers
boosters = ""
count = 0
if len(booster_list) > 0:
for booster in booster_list:
count += 1
boosters += f"\n`{count}` {booster.name}#{booster.discriminator} `({booster.id})`"
embed = discord.Embed(title=f":boost: {ctx.guild.name}'s boosters" ,description=boosters ,color=0xd40000)
await ctx.send(embed=embed)```
@potent jetty
in where?
I hope there is no error in this 😩
if booster_list:
for index, booster in enumerate(booster_list):
boosters += f"\n`{index + 1}` {booster.name}#{booster.discriminator} `({booster.id})`"
idk how to work with enumerate 😭
and you can just do if booster_list:
yeah
and im pretty sure you can make enumerate start at 1
so you wouldn’t have to increment
about that I tried to keep it simple for him cause it won't make a difference
what's the difference between for i in some_list and for i in enumerate(some_list)?
np :D
!d enumerate
enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.
```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
``` Equivalent to...
oh returns a tuple
in an enumerate you don't need to define the index above, you can just do
why index then
!e ```py
letters = ['a', 'b']
for index, letter in enumerate(letters):
print(f"index={index}\nletter={letter}")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | index=0
002 | letter=a
003 | index=1
004 | letter=b
I see example and it returns a list of tuples from what I see
@slate swanso this? py @commands.command() @commands.has_role('Mod') async def clear(self, ctx, amount : int, user: discord.Member = None): channel = ctx.channel await channel.purge(limit=amount, check=lambda m: m.author.id == user_id) Embed=discord.Embed(title=f"✅ | Deleted {amount} messages", color=0x228B22, timestamp=ctx.message.created_at) await ctx.send(embed=Embed, delete_after=10)
as you can see in this example, the index for the letter a is 0
its an iterable that returns a tuple
import discord
import time
wait=time.sleep
client=discord.Client()
@client.event
async def on_message(message):
if 'hello' in str.lower(message.content):
await message.channel.send('Hello!')
client.run('lol u thought')
```why does my bot spam "Hello!"
it by itself doesn’t return a tuple
oh
you still did not define who user_id is
it shouldn't send anything
why not
because your bot doesn’t check if the author is itself or another bot or whatever
it does work
how come
how do i fix this message?
you just shouldn’t do it
so i put the id in the user id or no? sorry, getting back into this
string?
!e
print(str.lower("HelO"))
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
helo
you put user in your params, not user_id
so user_id is undefined
what
so if I just put for some_variable, generator then it assigns value from 0 to as it goes on to some_variable?
?.
!e print(str.lower("REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"))
Pardon?
string
!e print(str.upper("hello!"))
@slate swan I think this isn't the place to do this
!paste can you send the code here?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ohhhhh i see ty
what's generator supposed to be
bro
like the enumerate
Why json.load(response.text) and not response.json()?
it's like
with command !paste?
discord.Guild in code
import discord
import os
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get('https://zenquotes.io/api/random')
json_data = json.load(response.text)
quote = json_data[0]['q'] + " –" + json_data[0]['a']
return(quote)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)
what
Can you read what the bot said?
no,
```py
code here
how is str not just a class
u watched that video aswell?
?????
yes
it is a class?
for some_index_var, some_value_var in enumerate(iterable), some_index_var will start at 0 and as it loops through the iterable it will increase by 1
import os
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get('https://zenquotes.io/api/random')
json_data = json.load(response.text)
quote = json_data[0]['q'] + " –" + json_data[0]['a']
return(quote)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)```
I'm just gonna shut up bru
I don't understand what you mean
oh if you pass something in lower() it works like that
you can also do discord.Guild.attr(guild_obj)
didn't know that
so like is there a reason for the index var to get the values or is it just how python works
but it isn’t recommended to do so
import discord
import os
import requests
client = discord.Client()
def get_quote():
response = requests.get('https://zenquotes.io/api/random%27')
json_data = response.json()
quote = json_data[0]['q'] + " –" + json_data[0]['a']
return quote
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)
```try this
def get_quote():
response = requests.get('https://zenquotes.io/api/random%27')
json_data = response.json()
return json_data[0]
probably just how python works
why's that
import discord
import time
wait=time.sleep
client=discord.Client()
@client.event
async def on_message(message):
if 'hello' in str.lower(message.content) and not message.author==client:
await message.channel.send('Hello!')
```i tried
ok tysm I learnt something new from you today :)
because you should use the instance that you have?
yw
well that didn't make it obvious
what
is there a difference?
I'm in a learning phase
You missed the closing string.
@slate swani put user_id py @commands.command() @commands.has_role('Mod') async def clear(self, ctx, amount : int, user_id : discord.Member = None): channel = ctx.channel await channel.purge(limit=amount, check=lambda m: m.author.id == user_id) Embed=discord.Embed(title=f"✅ | Deleted {amount} messages", color=0x228B22, timestamp=ctx.message.created_at) await ctx.send(embed=Embed, delete_after=10)
!e
string = "aaa"
print(string.upper())
print(str.upper("aaa"))
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
001 | AAA
002 | AAA
no difference?
sir I'm sorry but I don't think most of us understand half your questions. Try being a little more clear
typehint it to an int not a discord.Member
yes but you should use string.upper()
it still spams
oh now I understand his question
it gives same output but probs efficiency of doing the task differs
dude it's literally in your error
Check if message.author.bot and if it's True then return.
yeah that's what I meant
learn basic python
lmao
so like this? py @commands.command() @commands.has_role('Mod') async def clear(self, ctx, amount : int, user_id : int = None): channel = ctx.channel await channel.purge(limit=amount, check=lambda m: m.author.id == user_id) Embed=discord.Embed(title=f"✅ | Deleted {amount} messages", color=0x228B22, timestamp=ctx.message.created_at) await ctx.send(embed=Embed, delete_after=10)
AY IT WORKS TY

^
well it was a good question ig but you asked in wrong channel lol
yes
like it's better like:
if hello is None:
instead of
if hello == None
You didn't ask "how?"! You're my favorite person.
😂
tysm
it has same meaning as far as ik
yw
well output is gonna be same
it is, but by PEP rules it should be is None
I just saw people saying it here and like- I asked
what is PEP rules
is is for comparing singletons
I'm usually not here to get help it was just situational
!pep
pep_number
uh
epic
something that doesn't matter it's just "use it cuz it's better"
^
like the situation before about str.lower
@slate swan, it kinda worked?
tysm anyways
well I'll give an example:
a = "hi"
b = "HI"
print(a is b.lower()) #prints False
print(a == b.lower()) # prints True```
there is a difference you just need to understand it and idk how to explain it
you're making me crazy
you can change how == works for objects but you cant for is
asks what pep rules is
explains pep
I was explaining this
what he did there is not a pep
those are 2 fundamentally different things
it’s just uh.. python?
oh wait what
and I'm not even a pro
is and == are different things
they just give same output in certain scenarios
I was telling that
can anyone send me the scrit of turning the bot online
nah I'm gonna learn c# I'm out
but then you would say:
a = "hi"
b = "hi"
print(a is b)``` should also return False but it will return True
its just you gotta understand it deeper
its probs gonna be more complex if you dig deeper
tru
bro what. Just google how to make a discord bot and you get like 100 results with that
!e ```py
class Object:
instance = None
def new(cls):
if cls.instance:
return cls.instance
cls.instance = super().new(cls)
return cls.instance
obj1 = Object()
obj2 = Object()
print(obj1 is obj2)
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
True
something to do with memory allocation
oh i forgot google existed cuz im so into this cu zmy friend told me if u wanna learn this
my CS teacher taught me
I mean its fine to come here but like google will be better for that
channel died. Nice
lol
!e
list1 = []
list2 = []
list3=list1
if (list1 == list2):
print("True")
else:
print("False")
if (list1 is list2):
print("True")
else:
print("False")
if (list1 is list3):
print("True")
else:
print("False")
list3 = list3 + list2
if (list1 is list3):
print("True")
else:
print("False")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
003 | True
004 | False
hello any idea how i can make this work with id
hm
await message.channel.purge(limit=)```
you mean with the channel's id?
this code it remove msg from the channel that the msg sent in i want to make it remove msg from the channel id that i gave to the bot
yessir
i have this
so you can replace message.channel with bot.get_channel(id)
member_channel = bot.get_channel(886784755083907082)
await message.channel.purge(limit=)```
this would also work if you replace message.channel with member_channel
yup thanks i will test it out then
and pass something in limit
yup i know thanks alot
yw
i got this problem
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.```
import os
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get('https://zenquotes.io/api/random')
json_data = response.json()
quote = json_data[0]['q'] + " –" + json_data[0]['a']
return quote
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)```
pip install pillow or python3 -m pip install pillow
this isn't the right channel though
bruh what's with the ᓚᘏᗢ gang
.catify muhaha
and 'yalm'
there i'm in 😎
lesgo
Can a discord bots code have 2 languages for example js and py and both parts of the code will work?
If you can find a way to make both languages run at the same time you can
Which is currently never done so you’d be making a massive breakthrough in technology if you pull it off
lmao
how can i make bot respond to mention i have tried if client.user.mentioned_in(message): but if someone pings everyone bot responds too.

Bru
Because an everyone ping included the bot
The correct way would be to set the prefix, but seeing as you’re using a client and not a bot you don’t have access to a prefix
I recommend you switch over to the commands ext as it allows you to set commands easier and more cleanly
It also included tons of extra functions
Just replace client = discord.Client() with bot = commands.Bot(command_prefix=“prefix here”)
Make sure to add an import from discord.ext import commands
And replace all instances of client with bot
no because i heard discord.Client
is bad
It’s not bad
and i have that imported too
That's what you're using right now
Here is what the differences are https://vcokltfre.dev/tips/clientbot/
commands.Bot
You’re using client
According to naming conventions, you are using client and not bot
It does not matter
client is an variable
Naming does not matter in this case
nope
Not in this case
Always, it’s always important
Someone who looks at your code needs to see in the blink of an eye what a variable means
It does not matter if you call your commands.Bot instance client in this case
If you call your Bot client you are not doing that
i can have luc = commands.Bot and that wouldn't change anything
But it doesn't matter
If somebody is reading my code they would always start from the top
Except anyone who sees your code has no clue what in the world Luc is and will have a hard time trying to help you or maintain your code
If you share a snippet of code like you did now which did not include the line I assumed you used discord.Client
Even tho you are using bot
See why naming is important?
You're the only one who does that though
Look in this channel
People name it client but people understand they're using commands.Bot
That's just how it is
Me and many others have been trying to remove this bad habit from everyone
It’s a bad habit, it’s bad naming. The most essential thing with programming is making code that you and anyone with a slight bit of knowledge can understand
And not have to guess
Can you show me the other people who have been doing this?
That sounds stupid
@vocal plover
Look at their website
So one person
Count me in as well
lmfao
Can I have multiple examples?
pep8 mentions about good naming
Naming your .Bot client is just plain stupid and confusing for whoever is reading your code
it’s not really stupid
I’m sure @maiden fable is on this too
You believe me now?
Still confusing for whoever reads the code from a snippet where it's not specified that client is Bot
!zen 6
Readability counts.
Thank you 🙏
No because I asked for multiple examples
Hah didn’t know that command
Me neither
I gave you multiple people who are in for this
Bot has all of Client’s functionality and you would be able to tell if they’re using Bot or not from a code snippet
Not always
Let me show you
yes not always
Okay so 2/3 people
but does Bot add something new like api calls?
You don't know how to count 😟
it doesn’t
Right here @hasty iron look at my response
5*
List me the people who have been trying to fix this specific issue
Bot or Client is not really relevant there
Me, sebkuip, vco, hunter, the admin just now, etc
you can check if the bot is mentioned with either
So 5 people. That's really not that much
Look, we're not going to get into an argument with you here, it's not productive and you're just wasting our time. Name your variables what you want, but if you want your code to be readable, you should be descriptive with your variable names. So use client for discord.Client and bot for discord.Bot
^
Do what you want, but drop the subject here, since you're just wasting time now
arguing for the sake of argument
discord.Bot, shitpycord vibes
😂
lol
xd
Thanks
this channel is hilarious, like, i dont even need to go to the circus, the circus is right here! yall guys madlads, arguments like are what keep me alive everyday
wtf
hahahahahahha 😐
😐
😂
ok then 😆
does anyone know if the requests module can be used to edit discord messages?
Why would you wanna do that using requests and not a discord wrapper for python
Like dpy
how can I remove roles from a user whenever a textchannel is deleted?
channel_srch = discord.utils.get(ctx.guild.channels, name = new_channel_name)```
this is what I have so far
@client.command
@commands.has_permissions(kick_members=True)
async def kick(ctx, member : discord.member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{user} Has been kicked!")
@client.command
@commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f"{user} Has been banned!")```
Don't recommend it but yes.
could someone help me with the commands, they do not seem to be workin
anyone know what why this script is giving me a type error?
discord.Client() not discord.client()
ohhh
you watchinghttps://www.youtube.com/watch?v=SPTfmiYiuok
Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
🚨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables
Along the way, you will learn to use Repl.it's built-in database and cr...
discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\david\Desktop\dooby do\sust.py", line 15, in on_message
member=str.split(message.content,' ')[2]
IndexError: list index out of range
```why is this happening
yeah lol
Yikes bad tutorial.
Let's just say there are better one but it's not the worst.
na it's not a bad tutorial but it ain't the greatest
lmao ye
dont use this
wym
??? its not a bad tutorial?
nope
how
"but it ain't the greatest"
yea how
This is prob the best one -> https://vcokltfre.dev/
Made with love by one of the helpers.
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.
How do I run a tkinter GUI simultaneously while running the discord bot?
everything in that turotial is outdated and not good
hosting using repl.it and that site that pings it
message = str(message.content)
message = message.split(' ')
member = message[2]```
thank you 😊
lmao no, it's not outdated everything that's done in the vid is still usable weirdo
yea its only usable, not even efficient with whats available now
what would you recommend besides using repl and pinging with uptimerobot?
Never mind i change my mind it's a bad tutorial. He is making commands inside on_message
getting an actual vps
AWS or an actual VPS
lmaooo true ab that
aws is free for 1 year i think
if ya'all so smart help me solve this problem, and yes it has perms
If you got a credit card though, not pretty common in the EU
channel_srch = discord.utils.get(ctx.guild.channels, name = new_channel_name)
member = ctx.guild.members
if channel_srch == None:
await member.remove_roles(role)```
How do I make a system that removes roles from a user once a text channel is deleted?
cant help you just by looking at code
lmfao
You don't really give anything to go on besides "it's not working".
@midnight chasm no wonder you think that tutorial is good
would this also be a vps?
your @client.command is missing () at the end
Damn sasuke is on. 😂
You should be using Bot() not Client()
Bit overkill but yeah.
whats this lmao
changed that after asking a friend still didn't do it
whats the error its sending
what
its a server box
idk what that is but what we are talking about is a virtual private server
async def tasks():
await client.wait_until_ready()
anotherfunc()
gui.main_gui()
def main():
client.loop.create_task(tasks())
client.run(BOT_KEY)
How do I make it so I can run a gui alongside discord bot? It doesnt work as it runs the gui but does not load disc bot
Wait isn't that just internet switch lol
😂
Cool pycharm added "Tips of the day"
oh I was thinking of the one you can use from home
bruv
like actually buy one
here are all the vps we recommend
Well a vps technically is just a pc.
ye
@kindred epoch no error with the ban/kick
Isn't a raspberry pi always an option
i don't get it
...
How about the red line lol
bro....
user isn't defined and requests is not async. Use aiohttp
@midnight chasm can you also invite me to the server ur bot is in
client gets defined twice aswell.
so i can first kick some ppl and then ban
😂

yeye
like you though i wouldn't setup perms
lmao i was joking, might just want to add some perm checks
You're defining client as discord.Client() and commands.Bot()
Just use commands.Bot()
^^
Just all around you shouldn't copy code
Is there a way to run a gui simultaneously with discord bot? ive tried using tasks but it doesnt seem to work
oo maybe he started with that video, thats why he not hating
you ain't helping
Why would you need a task? Just use sub processing
Did you even read what I said before that
😂
? wym
ye dude
Thats good
change discord.Client with commands.Bot()
I got a website as GUI using sub processing
No just delete your discord.Client() line
just use this
bot = commands.Bot(command_prefix='.')
oh i searched it up u mean just run it in the background as another process
that acc fixes so many problems
Yep
you wouldn’t need a subprocess if your gui lib supports async
If i knew this while doing another project bruh u dont understand my pain
i didnt know subprocessing was a thing oooof
Hahaha, sub processing is pretty neat allows you to do nice things. But essentially it's just running 2 scripts without the need to click them both, also automatically they output to the same console. You can disable that of course.
even 5
You could prob run a discord bot on a usb stick.
yes but a vps is better
yeah im reading into docs acc so sad i didnt know before, ty alot
Im not planning on doing it im just wondering if its possible
yes? ofc it is
Prob good for like a good 4k servers depending on what you are doing RAM and internet and SD card will limit it
im wanting to make it so when you use the help command it sends my bot's help message and reacts with an emoji, then if the user reacts with the same emoji it deletes it, can someone send me some working code for this? I've tried asking in here multiple times and tried a bunch to figure it out, ive looked for tutorials and i cant find anything. pls send me some to look at so i can learn how it works
I hope you will finish it one day!
thats not helpful
lmao
💀
and to answer your question, no
i need some code to break apart tho
code your own code
what have you got so far
bcs it didnt work
and you expect us to just hand you code
that’s not help, that’s spoonfeeding
try it yourself, if you get stuck, ask for help here
don’t just give up and try to go the easy way
i have, nobody's help freaking works at all
"how to get python code"
show us ur code part ab it already
probably because you didn’t understand
you can keep sending your code and errors until you get useful help
Most people here are all self taught...
ill show you my code
you dont know how many times ive done that already
how many times
Have you tried the docs?
the docs won’t have a whole guide on what he wants
just send ur code, we'il see what we can do
also, it really seems like the only answers im getting are "go check the docs" or "try this, i have no idea if it will work or not"
dude just send your code and the errors you get
If you can name the function that will wait for a user to react with a reaction i will send you my class to guide a bit.
bruh?
on_reaction_add
Looking at the code you've sent before
that’s an event name
on_reaction_add only takes a reaction and user parameter not ctx
@fallow mauve
mhm
i really wish someone would have told me that before, but everyone has told me to use it...
Nobody has told you to use it
I suggest taking a look at the docs again or do some more research since i practically gave it away.
i wonder who is this "everyone"
ive looked at the docs, and ive done research, ive done all of that, it didnt work
@fallow mauve
!d discord.ext.commands.Bot.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/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
You were told it doesn't take a ctx parameter
what
;-;
dude are you ignorant or what
discord.ext.commands.Bot.wait_for if you want a time out, this is what i recommend.
discord.on_raw_reaction_add use this if you want the reaction to always stay there.
im having a bad day alright?
It's okay but we are not a channel that is just going to code it for you or literally give the code.
so what do i use instead of on_reaction_add?
Why would you not use on_reaction_add?
I think i explained it here pretty clear.
Since that event kinda sucks?
there is an example in wait_for’s doc page on how to wait for a reaction
how does it suck
async def tasks():
await client.wait_until_ready()
ct.create_tables()
def main():
subprocess.run("python utils/graphical_interface.py")
client.loop.create_task(tasks())
client.run(BOT_KEY)
the subprocess isnt running in parallel the client.run is still being held :C, howd u get ur website to run simultaneously
i might be very dumb rn
Well for bigger bots that event is pretty bad.
uh
asyncio has subprocess?
@fallow mauve Check the docs for wait_for it basically gives you what you need
!d asyncio.create_subprocess_shell
coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Run the *cmd* shell command.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_shell()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_shell "asyncio.loop.subprocess_shell") for other parameters.
Important
It is the application’s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. The [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote "shlex.quote") function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands.
Use this ```py
process = subprocess.Popen("python utils/graphical_interface.py")
there it is
why are you even using subprocess
omg it works
acc love u my guy
Can anyone provide me an example of discord.py v2.0 button code? I am struggling with a button. I dont like it ;/
i need to run gui alongside discord bot
its for school project, im doing something discord related but it must have a gui
does your gui lib support async?
Is subprocess blocking? Never had any issues though since i run it in a coro anyways.
im using tkinter
running something inside a coro doesn’t make it non-blocking
oh ok
ty guys u made me save so much time love u
I understand but if i do run the process shouldn't it instantly block the whole bot? Since it runs just fine.
Popen itself doesn’t block the event loop
but some methods inside can
if you use asyncio.create_subprocess_shell you can avoid that
Hmm i will def use the asyncio version later.
Is there any documentation that was created for discord.Interactions specifically buttons?
Have you tried their discord server?
dpy discord?
discord interactionss
interactions is in the dpy lib
dpy lib?

class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
I meant documentation for buttons
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Thank you
I was on the stable branch accidentally
from discord.ui import button, View, Button
from discord.interactions import Interaction
@client.command(aliases=["bj"])
@commands.max_concurrency(1, per=BucketType.user, wait=False)
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def blackjack(ctx, coins):
await Interaction.response.send_message(f'{coins}')
Error
AttributeError: 'CachedSlotProperty' object has no attribute 'send_message'
ok i looked at the docs and i dont know whats not working here, theres no error at all it just wont delete it:
Um
Why do you have an event inside a command?
that’s impressive, you were even given the docs of wait_for
^
yes i do
Hello, I wanna make a bot that announces who joined the voice channel any idea how to do it?
this is so advanced, why is it all classes and stuff. I wish it was like buttons="this" and thats it
it’s not advanced
and you’re supposed to know how to use classes and how subclassing works when using discord.py
yeah, python is simple but these guys make it overly complicated sometimes, i get ya
but why go through classes and all that stuff, i want to have less lines of code for a button
because that’s how it’s done in dpy
Im glad you understand. The unofficial discord button module is much easier than the official, so why should i bother with the official one?
you could use a garbage third party lib
exactly lol there is no difference, i dont get it
idk, ive never used buttons, but whatever, ill pretend i do
nope there is a huge difference between an official implementation and a wannabe
how is the unofficial worse than the official?
I want a way to use the buttons without having to create a class for it
have you seen or read some source code of those libs
;/
can anyone help me with a problem i have with a command for my bot?
im gonna stick with the poor mans way
does anyone know how to get input from a user?
what do you mean by that?
like if im making a quiz
and i need to know if they said a, b, or c
how would i check that
!d discord.ext.commands.Bot.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/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
then compare what they sent
make sure you have the check as well
I have a problem with one of my commands. So i have a simple kick command. So when the bot joins the server it like gets its own role. When i add the kick members permissions to that role i get a Forbidden missing permissions error when i do the command. But when i add the admin role which has all the permissions the kick command works perfectly fine
sorry so reply = bot.wait_for(message, check=None)
well you need to have a check
and when it says message do i have to say the right answer or just message?
it returns a coroutine
await it
await bot.wait_for?
yep
?
should i say 'a' or message
hello every1
hi there
hows it going
im a bit confused of whats inside the ()
in message do i keep it as message or do i check the answer
and for check do i compare it to the right answer or what
so there is a question and if some1 says the answer the bot will reply to the message and say its correct?
Ur doing it right
?
Ur current code it correct
Thanks
you know what, you are right man
this libs are actual trash, ama use the official, its actually easier
Yea, don't even bother with extensions lmao
They implemented them very poorly, and it takes a lot of lines to send one dropdown lmao
Compare that to the one from discord.py its a lot more cumbersome
Yo Guys,
Is there a problem with having multiple events? Because it seems like my on_member_join event isn't working. The other one does. Can someone help?
@bot.event
async def on_member_join(member):
guild = bot.get_guild(myIdIsHere)
channel = guild.get_channel(myIdIsHere)
print("It do be workin' tho!")
Like I don't get a print. Semms like the event doesn't work
Do you have member intents enabled?
Ohh wait.. yess I have it now. There was a mistake on the intents. Thanks!!!
class Counter(discord.ui.View):
def __init__(self):
super().__init__()
self.number = 0
@discord.ui.button(label='Press', style=discord.ButtonStyle.red)
async def count(self, button: discord.ui.Button, interaction: discord.Interaction):
self.number += 1
await interaction.response.send_message(f"{self.number}")
how do i edit the message instead?
edit_message probably
this is the error i get when i do that
await interaction.response.edit_message(f"{self.number}")
TypeError: edit_message() takes 1 positional argument but 2 were given
i made a bot in repl
Don't we all sometimes
lol
Without errors and code we can't guess what you need help for..
can u take a look at it?
i think indention error
name error
Just send it xD
module not found error
ok i will send the link to the repl u will only have read access
Share the code
no just send the code
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok
@client.event
async def on_message(message):
if message.author == client.users:
await client.process_commands(message)
role = client.users(822985879243980870)
if role in client.users.role:
msg = message.content.lower()
Last command indentation is not correct
client.users 
I think i get points for that i called it.
Yup
im trying to make it so only someone with a certain role will be able to use word trigger
Is this code from freecodecamp again?
no
i made this with someone
@client.event
async def on_message(message):
if message.author == client.users:
await client.process_commands(message)
role = message.guild.get_role(822985879243980870)
if role in message.author.roles:
msg = message.content.lower()
should i put the name of the role as a string
Sorry but i'm not going to help with an on_message command bot i recommend doing some more research first.
bruh
is there something better than on message
what a reason to not help somebody
the person who helped me make this is using old libraries
personally i dont like them but he's better than me so
does anyone know how to make all users that have the bot connected to their discord join a server? Example for what im saying:
"Join servers for you"
and then how to register when someone does that
I mean you are already using it but then you also got a message split that checks for if the command that is executed is the command that is being executed.
guilds.join scope
mind sending an example
I figured, https://vcokltfre.dev/ I recommend using this.
Yes, it's a pretty short tutorial but it will give you the general idea.
thx
https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes https://discord.com/developers/docs/resources/guild#add-guild-member look at these two
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
i appreciate it
ok i have figured out that im doing wrong
i will make custom commands instead of word triggers
that will work better
🥳
How can I get the clean_content from a string?
!d discord.Message.clean_content
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.
This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.
But isn't it for messages? I want to use it for variables
Thanks!!
@bot.command('join')
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
@bot.command('leave')
async def leave(ctx):
await ctx.voice_client.disconnect()
Anyone know how to make an if statement where the conditional is if its connected to a channel....?
is there a way to remove the button once i am done using it rather than just disabling it?
What is "it's"?
I recommend printing ctx.author.voice.channel
See what result you get if it is in a voice channel and if it is not in a voice channel.
wait nvm you can't do that ugh lemme search it up
actually that might work
async def is_connected(ctx):
try:
return ctx.guild.voice_client.channel
except:
return False
oh
if await is_connected(ctx):
...
but isn't that just the same as me printing ctx.author.voice.channel
That's why i said nevermind.
Whats the point in defining a new variable when you can just return ctx.guild.voice_client.channel
I've got no idea.
Use the members property of ctx.author.voice.channel which returns a list of members currently inside of the voice channel, then check if ctx.me is inside of the list
I'm new to python so bear with me... if i do this async def is it possible to write do:
if is_connected = none
.....
elif:
pass
This would only check if it is connected to a single channel, right?
Yes, the channel which the ctx author is in
I think he wants to do it so people cannot move the bot around.
I gave you an example -> #discord-bots message
To me it just seems like they want to check if the bot is in a channel before leaving or joining
Although not sure
yeah smth like that
So then just do what I said
Yep.
How do I do that....
members is a property of voice channel, you access it via dotnotation or, getattr. Ex: Voicechannel.members. This returns a list of members. [member1, member2] you would check if ctx.me is inside of said list
You can do this with an in statement
!e ```py
list_of_members = [1, 2]
if 1 in list_of_members:
print("yes")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
yes
Won't this also return an attribute error if the user executes the command whilst not inside a voice channel?
👍
Simple check fixes that
True true.
i.e if author.voice is not None: ...
why not just if author.voice: ...
But a None type is false
You can check if its truthy, sure but its a preference
i want to restrict a word trigger
to a certain role
if message.author.id == 872976347369201765:
msg = message.content.lower()
ik the .authoir.id only looks for a specific user's id
but what can i do if i want to look for a role
class shush:
def delete(channel, message):
r = requests.put(url=f"https://discord.com/api/v9/channels/{channel}/messages/{message}", headers=headers)
if r.status_code == 200 or r.status_code == 201 or r.status_code == 204:
print(f"{Fore.BLUE}>{Fore.RESET} Deleted {message}{Fore.RESET}")
@client.command()
async def massd(ctx):
await ctx.message.delete()
ids = open("ids.txt","r").read().splitlines()
for message in ids:
del = functools.partial(shush.delete, ctx.channel.id, message)
threading.Thread(target=del).start()
im trying to make my bot delete messages with requests but it doesnt work and i get no errors any ideas?
del is a registered keyword on python
I would suggest you use something like aiohttp instead of requests since it is blocking
how would i use aiohttp
Search for documentation
@slate swan that line should be inside a function
How to check the number of messages a discord.py member sent?
I want to do a command that when a member sends a message (or a number of members) blocks the channel or channels to avoid spam.
Yes but is for avoid raids, for example the bot send a number of messages and the command block the channel for cancel the raid, for security
Is for help moderation
Up to you how you handle it, slowmode on command, remove message perms
No for example block the send messages perms when the bot detect a number of messages, i want to do that
Number of messages from 1 person right?
Yes, but if possible, I would appreciate it if the bot could detect those of several members
Use a dictionary and in on message you can increase the counter
Then just reset it after x time or whatever
I might make a plugin for it on my package, seems like a nice idea tbh
Ok thanks
But for now thats how you can do it
Idk when imma make this plugin, but I can link you a place to wait for when I make my next release
Ok
If u r talking about the naming bot, client thing and stuff, well sure then :D
(I was sleeping since it was nearly 2 that time)
Hi, does anyone know how to help me with this. I am trying to make my discord bot leave a vc but it isnt working.
Ghost ping
@client.command(pass_context=True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.message.guild.voice_client.disconnect()
await ctx.send("I left the voice channel")
else:
await ctx.send("You need to be in a voice channel to do this")
does it send "YOu need to..... everytime?
No, it send that it disconnected from the vc but it dosent leave
also , pass_context is not longer required in the recent versions
depends on your discord.py version and not python version
its weird that the bot does not disconnect since according to the code , it must disconnect first and send "I left the ... " message
did you rerun the code after saving?
yeah, i dont know why it just dosent work
It disconnects from the server but its because it times out
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Do i need to import something to make my discord bot leave a vc. I already have discord.py[voice]
hello
Hey @graceful gorge!
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:
!code-block
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.
#bot-commands
I am trying to make my discord leave a vc but it dosent leave it. Is there any obvious way to fix it that i didnt notce?
@client.command(pass_context=True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.voice_client.disconnect()
await ctx.send("I left the voice channel")
else:
await ctx.send("You need to be in a voice channel to do this")
how can i make reload cmd?
did u download it?
reload command for what?
download what
the module
i didnt do anything to it, its been working ever since i started using it
what does the error say
did you download it though?
i dont remember
bruh
its been working every since i started using it
and i didnt uninstall anything recently
it'll refresh the bot's cmd list without shutting down the bot and running it again