#discord-bots
1 messages · Page 458 of 1
thats not how you use cogs
classes are not only in dpy
and you forgot to add the self parameter

@bot.command()
@commands.has_role("Giveaway Handler")
async def gstart(self, ctx, Channel:discord.TextChannel, endtime):
```like this?
yes
but i didn't faced any problem by that
i only have a problem that is the StopTime is not changing after using global
yesterday i discovered the wait_for command, but does that one also check for more than one time? cause im making a quiz where dont have just one try
and like i said, use a dictionary instead of global variables
inside the function or outside?
what i should change here?
So that you can access and modify it from anywhere in the class
@steep estuary https://stackoverflow.com/a/19158418
!e ```py
class Foo:
def foo(self):
print("Foo method")
Foo().foo()```
what my command is not working now :/
You need to initialize the class
oo
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
Foo method
self is taking a place when using command
in discord py, is there a way to global variables for command groups?
!e
- Remove globals, they hurt

- You can say
selfis like an instance of your class, where you can access any of the class items from anywhere
This is how we define classes ```py
class X:
def init(self): # init method, we'll initialise our vars here
self.a = 1
self.b = 2
self.c = [3, 4]
Now make a method inside class ```py
def foo(self): # self is always passed as first parameter
print(self.a) # I can access `a` inside class
self.a = 100
You can also access methods into other method, like ```py
def bar(self):
self.foo() # calling other method from the same class
print(self.c)
del self.c[0] # can also modify anything
Making an instance of the class ```py
x = X() # x is called an instance of the class, you can create as many as you want
# also our __init__ is called here only
x.foo() # calling method of the class
x.bar()
# also
x.a = 99 # modified it outside the class
print(x.a)
This is how classes work, and if you didn't know that, you should learn oop first before dpy
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 100
003 | [3, 4]
004 | 99
@steep estuary ^
hmm
is there a way where i can make a list with a method, then use that list in other cmds that is the same cmd group?
same cmd group means? A group command or a cog?
why this StopTime is not changing wht should i use instead of global to change it ?
group cmd
did you check the link which i sent
If they're in a class, does not matter they're normal functions or commands or groups, you can access them
yes but wht should i use instead of global
i am not understanding
but that
You just ignored the whole paragraph I wrote 
a dictionary
i saw that
Just like I defined a list in the class, self.c, similarly define a dict 
giveaway_config = dict(stop_time=0, giveaway_channel=None, participants={}, giveaway_active=False)
k
call dict method use json like dictionaries
why we should use that cuz dictionaries don't want global to change?
aaaaaaaaaaa nothing happening 😫
using dict(x=10, y=20) is more cleaner than {'x': 10, 'y': 20} IMO
async def help(ctx, message=None, *, member=None):
if message is None:
role = discord.utils.find(lambda r: r.name == 'Saus', ctx.guild.roles)
member=f"{ctx.author}"
if role in member.roles:
embed=discord.Embed(title="Hoi! Hoe kan ik je helpen?", description="Zie hieronder de algemene commands. Gebruik !help (command) voor meer info!", color=discord.Color.red())
embed.add_field(name="**Openbare commands:**", value="", inline=True)
embed.add_field(name="!help", value="Dit commando.", inline=True)
embed.add_field(name="!ping", value="Ping van de bot.", inline=True)
embed.add_field(name="!verify", value="Verifieren op de bot", inline=True)
embed.add_field(name="**Moderatie commands**", value="", inline=True)
embed.add_field(name="!ban (persoon) (reden)", value="Persoon bannen van de server.", inline=True)
embed.add_field(name="!unban (persoon)", value="Iemand unbannen", inline=True)
else:
embed=discord.Embed(title="Hoi! Hoe kan ik je helpen?", description="Zie hieronder de algemene commands. Gebruik !help (command) voor meer info!", color=discord.Color.darkblue())
embed.add_field(name="!help", value="Dit commando.", inline=True)
embed.add_field(name="!ping", value="Ping van de bot.", inline=True)
embed.add_field(name="!verify", value="Verifieren op de bot", inline=True)
Ignoring exception in command help:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/bot.py", line 48, in help
if role in member.roles:
AttributeError: 'str' object has no attribute 'roles'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'roles'
hmm
that how i can call or use the Stop Time
does client.wait_for check for more than one message before quitting waiting? because im waiting for a correct answer and not any
It waits for the following message
of the author
Depends on how u made It
ok so i added a command to my bot which sends a subreddit post, but the problem is, it takes a while to send the post, as its running in an asynchronous environment. so im going to switch from praw to async praw, but will i have to change any of my code? heres what ive got(part of it is cut, obviously):
subreddit = reddit.subreddit("memes")
all_subs = []
hot = subreddit.top(limit = 50)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(title = name)
embed.set_image(url = url)
await ctx.send(embed=embed)```
Does mongodb blocks discord.py or slow somehow?
afaik it doesnt
actually nvm, i found docs about it
!pypi reddit
Depends on the db driver you are using
Hi, how can I add a method as a command? I've tried @commands.command() but "ping" isn't recognised
from discord.ext import commands
class LomiBot(commands.Bot):
def __init__(self, command_prefix, help_command=None, description=None, **options):
super().__init__(command_prefix, help_command=help_command, description=description, **options)
async def on_ready(self):
print("LomiBot online")
@commands.command()
async def ping(self, ctx):
await ctx.send(f"pong ({self.latency*1000} ms)")
if __name__ == "__main__":
lomibot = LomiBot(command_prefix="-")
lomibot.run(MY_TOKEN)
if you do that you'll have to call self.add_command inside the __init__
Bot classes cannot have commands like that. They were designed to stop it
What do you mean by "designed to stop it"? Doing my bot through a class is not the intended way?
Adding commands via bot subclass
So, If I wanted a class, should I get the bot as an atrribute instead of a subclass?
why not add the command after instantiating the Bot subclass
i am getting error here
ems.set_author(name=guild,icon_url=guild.icon)
```the guild has no icon
Sorry, I will try that, thanks
Try icon_url
!d discord.Guild.icon
The guild’s icon.
!d discord.Guild.icon_url
icon_url```
Returns the guild’s icon asset.
in 2.0.0a bruh
It says discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
remove self if the function is outside a class
Icon should always be available
basic oop
I get that, but ping is a method, not a function
So how should I do it?
I mean, I know how to do this with only functions, but I wanted to do it as a class because I believe is cleaner
then use a cog
Ok, I will check that, thanks
I converted it to bytes cuz I read this in the documentatio
this is taking the StopTime Only once it is not taking the changed value of StopTime
I tried that but it gave me a different error
!d discord.User.avatar_url
avatar_url```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, an asset for the default avatar is returned instead.
This is equivalent to calling [`avatar_url_as()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.avatar_url_as "discord.User.avatar_url_as") with the default parameters (i.e. webp/gif detection and a size of 1024).
this was the code I used when I used read()
This is their avatar as an asset
pls someone see this once
Yes that's how it works
so how do I give my webhook a avatar??
I told you
but i want to change it as per the user change it in command
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
but how i can insert a loop in it
can i make other to not send the message in a thread?
Any help towards this
@bot.command()
@commands.check(simple_check)
def BinaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
return (decimal)
async def binarytotext(ctx, *, args):
bin_data = args
await ctx.send("The binary value is:", bin_data)
str_data =' '
for i in range(0, len(bin_data), 7):
temp_data = int(bin_data[i:i + 7])
decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)
await ctx.send("The Binary value after string conversion is:",
str_data)
Recieving
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 81, in <module>
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1245, in decorator
result = command(*args, **kwargs)(func)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1412, in decorator
return cls(func, name=name, **attrs)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/ext/commands/core.py", line 217, in __init__
raise TypeError('Callback must be a coroutine.')
TypeError: Callback must be a coroutine.
[Program finished]
await it
Ah
wait
wth
R u replying to wrong person
How?
Did you catching the error anywhere?
In your bot file
Which commands?
All?
I mean
All cmds that you sent?
@slate swan y copy code
hey does anyone know how to write in python code within discord?
i know you need the and but forgot the command for the colourss
Can anyone answer this ^
!!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.
ahh thanks
yes the youtuber
Why? ```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
172.18.0.1 - - [08/Sep/2021 14:47:33] "HEAD / HTTP/1.1" 200 -
Ignoring exception in command warns:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 64, in warns
embed = discord.Embed(description = f"{member.name}, have {amount[0]} warnings.", color = 0x7cf7be)
TypeError: 'NoneType' object is not subscriptable
Pls provide more information such as your specific cmd codes
In your main.py
if msg.author is self.bot.user:
return
if channel:
await msg.delete(delay=20)
```help??? its delete the bots (its own) messages also
@client.command()
async def warns(ctx, member: discord.Member):
conn = await aiosqlite3.connect("testing")
c = await conn.cursor()
await c.execute("SELECT amount FROM warn WHERE userid= ?", (member.id,))
amount = await c.fetchone()
embed = discord.Embed(description = f"{member.name}, have {amount[0]} warnings.", color = 0x7cf7be)
embed.set_footer(text=f"{ctx.me.name} | {datetime.utcnow().strftime('%A %H:%M %Y-%m-%d (UTC)')}")
await ctx.send(embed=embed)
ok
The “TypeError: ‘NoneType’ object is not subscriptable” error is common if you assign the result of a built-in list method like sort(), reverse(), or append() to a variable. This is because these list methods change an existing list in-place. As a result, they return a None value.
Info from https://careerkarma.com/blog/python-typeerror-nonetype-object-is-not-subscriptable/
not working
Can I make a command that appears on the server creation date?
yes
when a guild was made?
!d discord.Guild.created_at
created_at```
Returns the guild’s creation time in UTC.
I created this command just to test, but when I send the message, its saying that the username is None, does anyone know why?
ID's are always intergers. Never put speech marks.
I also tryed as integer, but it said the same thing
Then the bot isn't getting the user
do you know if its possible to do the opossite? convert an username to id
i get this error```Ignoring exception in on_command_error
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 654, in set_permissions
overwrite = PermissionOverwrite(**permissions)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/permissions.py", line 542, in init
raise ValueError('no permission called {0}.'.format(key))
ValueError: no permission called color.
During handling of the above exception, another exception occurred:
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 845, in adduser
await ctx.channel.set_permissions(user, read_messages=True, send_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, color = 0xFF0000)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 656, in set_permissions
raise InvalidArgument('Invalid permissions given to keyword arguments.')
discord.errors.InvalidArgument: Invalid permissions given to keyword arguments.
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/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 441, in on_command_error
raise error
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: InvalidArgument: Invalid permissions given to keyword arguments.```
while using this command
@bot.command()
async def adduser(ctx, *, user:discord.Member=None):
if ctx.channel.name.startswith('ticket'):
if user != None:
await ctx.channel.set_permissions(user, read_messages=True, send_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, color = 0xFF0000)
embed = discord.Embed(description = f'Successfully added {user.mention} to this Ticket.')
await ctx.send(embed = embed)
else:
with open('/home/runner/EBOT/info/prefixes.json', 'r') as f:
file = json.load(f)
prefix = file[str(ctx.guild.id)]
embed = discord.Embed(description = f'Try the command in the following way:\nEg. `{prefix}adduser {bot.user}`', color = 0xFF0000)
await ctx.send(embed=embed)
else:
pass```
try colour instead of color
and you put color in the permissions of the channel
I dont think this is possible
@cold violet
oh yes
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 654, in set_permissions
overwrite = PermissionOverwrite(**permissions)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/permissions.py", line 542, in __init__
raise ValueError('no permission called {0}.'.format(key))
ValueError: no permission called color.
``` this part wasnt visible in terminal
thx
I didnt understand, can u explain again pls. Sorry for the late response
What I am saying is that I didnt understand what u explained in the message, so I asked to explain it
how should I use that in my create webhook line??
you're trying to access the avatar attribute of a user/member, which is the hash of their avatar
the avatar_url property of a user/member is the Asset associated with their avatar
Assets have a read method which is a coroutine, which returns the bytes of the image the asset represents
now it shows this
!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/stable/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
avatar=
I tried that and it didnt work, that was my first post
does anyone know how to steal emojis command?
Oh shut
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Thanks for telling me.
second for what?
but it is taking the StopTime value when the bot go online
after that whenever i change the value of stoptime
it is not changing the value of stopwatch written there
i don't know if think because im new at python
k
whats the meaning of cogs i dont quite understand it?
embed.add_field(name=f"Waarschuwing {i} gegeven door: {admin.mention}.\n",value=f"Ivm {reason}")
AttributeError: 'NoneType' object has no attribute 'mention' (Its about admin.mention)
This should be finely working right...?
Show where you defined admin
async with aiofiles.open(f"{ctx.guild.id}.txt", mode="a") as file:
await file.write(f"{member.id} {ctx.author.id} {reason}\n")
admin = ctx.guild.get_member(admin_id)
Sharing data between commands is easier in cogs but thats my opinion
!d discord.ext.commands.Cog
class discord.ext.commands.Cog```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
ty
where is admin_id there
Btw If you ask, I used the alphascript tutorial
should i learn python oop before making a bot?
you could, Its advised
Okay, so, copied or?
Basically yes 😂
mkay
https://paste.pythondiscord.com/enobisadot.py this is the code
And that isn't good
how do i get a message using message id
I know sorry lol
!d discord.TextChannel.fetch_message
await fetch_message(id)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") from the destination.
This can only be used by bot accounts.
yea
Most likely yes
but
it's a method of textchannel
@willow vine
discord TextChannel that is
I got to go hopefully you get it if not consider OOP!
check pins
i need help, i cant clear messages with this code-
import discord
from discord.ext import commands
@client.command()
async def clear(ctx, amount = int):
await ctx.channel.purge(limit = amount)
Please tell me how to fix it?
#python-discussion i asked u something
where did you define client?
import asyncio
import discord
from discord.ext.commands import Bot
Client = Bot('!')
@Client.command(pass_context = True)
async def clear(ctx, number):
mgs = [] #Empty list to put all the messages in the log
number = int(number) #Converting the amount of messages to delete to an integer
async for x in Client.logs_from(ctx.message.channel, limit = number):
mgs.append(x)
await Client.delete_messages(mgs)
Client.run(Token)```
client = commands.Bot(command_prefix='?', case_insensitive=True,)
how do i set a prefix with a command
gud
maybe watch yt?
just don't use case_insensitive
theres no case in it
i think
custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['.']
async def determine_prefix(bot, message):
guild = message.guild
#Only allow custom prefixs in guild
if guild:
return custom_prefixes.get(guild.id, default_prefixes)
else:
return default_prefixes
bot = commands.Bot(command_prefix = determine_prefix, ...)
bot.run()
@commands.command()
@commands.guild_only()
async def setprefix(self, ctx, *, prefixes=""):
#You'd obviously need to do some error checking here
#All I'm doing here is if prefixes is not passed then
#set it to default
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
await ctx.send("Prefixes set!")```
I don't know what's wrong with this command but i'm gettig a syntax error on the asyncpy @commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]") @commands.bot_has_permissions(manage_messages = True) @commands.has_permissions(manage_messages = True) async def massban(self, ctx, Optional[days : int] = 0, reason : str, *, targets: commands.Greedy[discord.Member]): with ctx.typing(): users = 0 for user in targets: users += 1 await ban(user, reason = reason, delete_message_days = days) await ctx.send(f"len(users) were just banned.", delete_after = 5)
i need one more help
i used a JSON file to store all the prefixes 
go ahead
json bad
ik
still better than dicts
how'd you type the code so fast xd
json is basically a dict if you use it as one
in some ways
when someone says the problem 10 sec ago
import asyncio
import discord
from discord.ext.commands import Bot
Client = Bot('!')
@Client.command(pass_context = True)
async def clear(ctx, number):
mgs = [] #Empty list to put all the messages in the log
number = int(number) #Converting the amount of messages to delete to an integer
async for x in Client.logs_from(ctx.message.channel, limit = number):
mgs.append(x)
await Client.delete_messages(mgs)
Client.run(Token)```
i said it already XD
@slate swan
I think he haven't understand.
How do i delete recent msgs in all channels by a member?
old code
thats the case.
wont work
then wait
?
client = commands.Bot(command_prefix='-')
@client.command(name='clear', help='this command will clear msgs')
async def clear(ctx, amount = 5):
await ctx.channel.purge(limit=amount)```
soft-ban them
Hm
oh
TextChannel.purge has a check kwarg
Well i am trying to ban/softban a member who sends msgs in almost all channels in under 10 seconds.
Deletw ownpy #this code will send "HI" for 3 seconds when the user says "HI" #discord.py rewrite #python 3+ include time @bot.event async def on_message(message): #Only continue if the message is "HI" if not message.content == "HI": return #Send HI back, and set it to a var BotMessage = await ctx.send("HI") #wait 3 seconds time.sleep(3) #delete the bot's msg BotMessage.delete()
There's a lot of fake discord nitro activity now a days
yea
time.sleep is blocking and that will raise a NameError
stop copying code and pasting it here
there are 2 NameErrors infact
anyone nows how to change the profile picture of a bot with a command ?
!d discord.ClientUser.edit
await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
If a bot account is used then a password field is optional, otherwise it is required.
Warning
The user account-only fields are deprecated...
i dont think you can do that
Writing instant code is not possible!
not working :(((((((((((((((((((((((((((((((((
Agreed!
you can
this
2 hours x)
change the pfp of the bot through the command?
writing snippets is
yes
@slate swan py with open('image.png', 'rb') as image: await client.user.edit(avatar=image)
Hmm
I don't have much time. Understand.
atleast give corrent examples or whatever you're sending
I'll try
tthx man
yw
@stuck flare clear code you gave me is not working
you can also get an image from the internet by sending a GET request to its url using aiohttp and then calling await response.read() which returns a bytes object
guys how to get message using message id without passing channel
@Client.command(pass_context = True)
async def clear(ctx, number):
mgs = [] #Empty list to put all the messages in the log
number = int(number) #Converting the amount of messages to delete to an integer
async for x in Client.logs_from(ctx.message.channel, limit = number):
mgs.append(x)
await Client.delete_messages(mgs)
Client.run(Token)```
This is not working :c
with open('image.png', 'rb') as image:
await client.user.edit(avatar=image.read())
```try this
yes because its old code
you need the channel ID to find the message
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
and you dont even need that
is there a way without having channel id
!d discord.TextChannel.purge does what you want for you
await purge(*, limit=100, check=None, 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/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
No (ig)
hm
i believe there is, but you'll have to use internals
do you know how to do it
let me see
bot._connection._get_message(message_id)
but i dont recommend using it
!d discord delete
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
there is the limit argument
read
I don't know why but this code keeps giving me indentation errors and I have unindented it all and re-indented it with no success.```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, days : Optional[int], reason : str, *, targets: commands.Greedy[discord.Member]):
users = 0
with ctx.channel.typing(): # <---- This line is giving me errors
for user in targets:
users += 1
await ban(user, reason = "Unspecified" if reason == None else reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))
await ctx.reply(f"{len(users)} were just banned.", delete_after = 5) # <---- as is this line```
oh why not
because you're using internals
hm okay let me try
what does that mean
I'm kinda noob ;-;
using private variables you're not supposed to use
oh why aren't you supposed to
because they're private..?
oh
i mean thats the convention
hmm okay
if an attribute starts with _ that means its private
like what i basically want is, if i unload a cog, the variable will be lost, so the msg variable is gone
oh
yeah idk how to use a database yet
and store objects in it
learn how to then
most people recommend postgresql for sql db and for no sql its mongodb
didnt work
That's Client.cached_messages only..? And also limited
oh wait forgot that existed
Hi. Does anyone know what the difference between nextcord and pycord? 🧐
For the development of a totally new bot, which one of the these are recommended?
Well I haven't used either so can't suggest
solved?
From what I've seen, both forks haven't had anything different from discord.py.
My question is more about the community around it, it seems that both try to solve the same problem
can someone tell the code for deleting the messages on the channel on which user has sent the clear command
!d discord.TextChannel.purge
await purge(*, limit=100, check=None, 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/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting bot’s messages
think so
if i have to make limit customizable, like if i want to delete 38 msg but that command is doing 100 msg delete
because you are telling it to delete 100 messages.
limit can be made a command argument, and do limit=limit
where limit will be the int(amount) the user passes in
does it work?
yes
wait i will try
aight
its showing error
and its not workin
limit is not accessed as pylance
😦
how tf is it on moiele
class Lobby:
def init(self, lobby_number, queue_channel_id, Team_A_channel_id, Team_B_channel_id):
queue_channel = client.get_channel(queue_channel_id)
Team_A_channel = client.get_channel(Team_A_channel_id)
Team_B_channel = client.get_channel(Team_B_channel_id)
queue_channel_members = queue_channel.members
queue_channel_members_mention = []
for member in queue_channel_members:
queue_channel_members_mention.append(member.mention)
@client.group(invoke_without_command=True)
async def lobby(ctx):
ctx.send("Lobbies Online.")
@lobby.command()
async def start(ctx):
random.shuffle(queue_channel_members_mention)
team_a = queue_channel_members_mention[len(queue_channel_members_mention) // 2:]
team_b = queue_channel_members_mention[:len(queue_channel_members_mention) // 2]
embed_lobby1 = discord.Embed(title="Teams")
embed_lobby1.add_field(name="Team A", value="\n".join(team_a), inline=True)
embed_lobby1.add_field(name="Team B", value="\n".join(team_b), inline=True)
await ctx.send(embed=embed_lobby1)
@lobby.command()
async def result(ctx, result):
result = str(result)
Team_A_channel = client.get_channel(870969338901954606)
Team_B_channel = client.get_channel(870969338901954607)
Team_A_members = Team_A_channel.members
Team_B_members = Team_B_channel.members
Team_A_members_id = []
for member in Team_A_members:
Team_A_members_id.append(member.id)
Monkeypatching
someone help in #help-cake
does someone khnows how to do a command like +addrole and it adds the role mentioned
how to add in a dict? append doesnt work
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild")...
so i have this mass ban command but I'm getting this errorpy NameError: name 'ban' is not defined ```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await ban(user, reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))
await ctx.reply(f"{users} members were just banned.", delete_after = 5)```
!d discord.Member.ban
await ban(**kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.ban "discord.Guild.ban").
Sorry, misread the error
if member is your mmeber object, you do await member.ban(**kwargs)
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
I think this is what you're trying to do but ban is an attribute of guild so you need to call guild.ban
its both
so for the ctx guild it would be ctx.guild.ban right?
it is loading your eco cog in the main file?
well your eco file is a cog
you can do
await user.ban(reason = reason, delete_message_days = days)
okay the command I'm using is ,massban 791394319075377243 757750333144563724 1 Testing and it's giving me py TypeError: ban() takes 1 positional argument but 2 were givenfor ```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await user.ban(user, reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))
await ctx.reply(f"{users} members were just banned.", delete_after = 5)```do i need to `user = user` in the ban await
remove user as the kwarg for the ban
its discord.Member.ban in this case
hey guys i have this thingy that appears when i do the +help my command is not +help actually i didnt do this command and when i do it it shows me this what is it and how can i remove it ?
help_command=None in commands.Bot()
bot = commands.Bot(command_prefix = "a prefix", help_command=None)```
thx ^^
think i'm just being dumb but i'm not following as I'm still getting the error```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await user.ban(user, reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))
await ctx.reply(f"{users} members were just banned.", delete_after = 5)```so your saying I should make it `await discord.Member.ban(user, reason = reason, delete_message_days = days`. also is there a way I could pretty up the arg declarations for days and reason
no lol. In your case, the Member is user. So it would be
await user.ban(reason = reason, delete_message_days = days)
well I tried that and still got the error
code?
testing it again removing user from the kwargs
okay well I think it's working. I got it to ban one of the two acc's I inputted. It told me it banned 0 ppl in the plain msg reply and it didn't send the embed at all```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await user.ban(reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.utcnow()))
await ctx.reply(f"{users} members were just banned.", delete_after = 5)```
days = days or 0 for this, im not sure if this would work, since you did not say days can be none, so if you don't give days i assume it would raise missing required argument, or bad argument
not the issue but just saying
users += 1 to get the list of members that the user mentioned you can also use len() on that argument
len(targets)
oh yeah
and you want it to reply to each member the user mentioned?
if he gave 5 members it would reply 5 times
yeah and does everyone khnow how like change the name of the bot with a command like +set name
For mass ban I wouldn't really suggest using anything after the commands.Greedy[] 
!d discord.ext.commands.Bot.edit
uhm wait forgot what it is
i want it to reply to the user who used the command yes. so if 5 ppl were mentioned it would reply 6 times (5 for each member and once for the len of targets)
i'm a new beginner i need a code like to examinate it like what i do
!d discord.Member.edit
await edit(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
use that but instead of member, use ctx.me to edit the bot
no errors for this?
Command: ,massban 791394319075377243 757750333144563724 1 Testing
Bot response: 0 members were just banned with reason 757750333144563724.
Code: ```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
for user in targets:
await user.ban(reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.utcnow()), delete_after = 5)
await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")```and it gave no errors. I tried making it ```py
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : Optional[int] = 0, reason : str):```but it gave me a syntax error (yes i'm importing optional and it works elsewhere i the cog
i didnt khnow how to do it in a code 😦
olay yeah the ids are being taken as the wrong argument
try mentioning the user
@flat solstice
It may raise bad arguement expected an int.
days:int
okay mentions worked
if it raises bad argument how would it give the message of how many users were banned?
await ctx.send(f"{'{emoji.done} Meme is running' if self.meme.is_running() is True else '{emoji.error} Meme is not running'}")
```why its sending `{emoji.done}` instead of emojis
If it's commands.Greedy set as discord.Member mentioning as many users as you want will always work but it's not really efficient to mention all the users let's say in the case of a raid 
And it'll just take long
why have if x is True
just if x should work
i edited it
it's still kind of what it was before
should I make it wait for a second or third msg. one which gives the reason and/or the amount of days to delete?
@bot.command()
async def ban(ctx, members: commands.Greedy[discord.Member], delete_days: typing.Optional[int] = 0, *, reason: str):
success = 0
for member in members:
await member.ban(delete_message_days=delete_days, reason=reason)
success += 1
await ctx.send(f"Banned the {success} members")
#error handler
``` I'm just thinking this may work a little better maybe tbh? Consider trying it and comparing to what you have ( edit as you want )
bare try and except with pass 
edit as you want
i'll try that but I was getting a syntax error when i tried making delete_days into a typing.optional arg altho i'm not sure why so I'll try it again. i'll let you know
Theres anyone that can help me with a addrole command pls i'm trying it dont want to work
!d discord.Member.add_role
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.
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, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
I told you discord.Role type hint
don't ban me for this, but someone may need it

in title can i use custom emojis?
I wonder how they didn't get muted for excessive emojis 
I'm dumb

i can't see them i don't have unicode royal pass
can anyone help me please? idk y but my bot calls the api 2 times at one command, whats wrong?
check if your bot is running on multiple scripts or not
thats all
what he meant was if ur bot is running multiple times
if not then show code
i dont think this is possible in my hosting, ill restart and check tho
should i send all of my code?
i restarted it and it happend again
Regenerate your token
ok, ill try
you're using a deprecated function, these functions are mainly userbot only functions
which indicates that you're using a userbot, which is highly against TOS and not allowed here
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Is there a wait for message function or corotine? I want to add in a criteria to a command that my bot waits for a reaction from the user and then if a reaction is clicked then the bot waits for the user to type a msg and then I can make use of the msg
Hey guys I'm trying to build a bot that pays music from a youtube url
I'm looking now into making playlist feature
did anyone already v done this ?
!rtfm commands.ext.Bot.wait_for
god
i meant
ugh
!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/stable/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
finally
thanks for this
yw
playing songs from yt urls is against tos
||!ytdl||
is discord really forcing everyone to move to slash commands if so im done being a developer and i know alot alot of people who agree
well you don't need to move to slash if you have a small bot bc you don't need to verify to get the message intent
if ur bot is not verified u can stick with the old commands system
otherwise you either have a good reason for discord to give you the intent (saying that u want it bc old commands were better won't work), either ur forced to use slash
My bot is growing and growing and im kinda scared about it should i start moving my commands to slash
yes
just for testing
unless u plan to never verify it and cap your bot's total guilds to 100
Yes thats how groovy got shut down
we cant help with that even tho its just for testing
pretty sure it's also against yt's tos
well looks like its time to start moving to slash commands (yuck)
ye
is there a way to set a string input as optional and to give it a default value? is it just string : typing.Optional[str] = "Deafault String or would I need to do something else
ye
okay thanks
if you add = "" it automatically converts to optional
or just = None
ye
well I've done this but it's not highlighting the str as green in the syntax but wrapping it in [] does
it doesn't need to be green if it works
yes
I moved everything to pycord
disnake >
disnake?
yes
!pypi disnake
disnake is another very good fork of dpy which is maintained by the creator of dislash
Oh man I hated dislash
in my opinion better than pycord
never used dislash so can't confirm
I see yea i moved to pycord because its d.py but forked and maintained
same with disnake
it has the exact same dpy 2.0 syntax with slash
The problem is it is import disnake and not import discord seems weird ngl
i mean, its ok, im gonna use it to convert to slash commands, but if disnake has slash commands then ill use that
it does
Pycord is more popular thats how i found it
if it does then theres no meaning of having dislash imo
¯_(ツ)_/¯
ik but eh
Seeinjg discord.py go is kinda sad now
Is there anything new cool in disnake that pycord doesn't have?
fr
dislash is still maintained probably bc there's some ppl still using it
what does pycord have lmao
idk all the new features of pycord lmao
mhm 😔
Nothing amazing lol
does it have the apps thing?
pycord does
I think it does have it yeah
disnake has that too
PyCord is most popular with over 300 stars and a lot of devs
i still hope for disnake to be at the top 😫
kinda like the name more too tbh
makes sense
cuz a yt'r owns it
Yes but atleast i know that they wont just drop the project for no reason like danny did
pycord didn't even bother to change the pypi description
¯_(ツ)_/¯
well, danny has been working on it for 6 years and that discord is pushing to many updates on the api
so imo its not his fault
only in the repo it's changed
True dat im just saying with the fall of the biggest and best wrapper for discord bots there comes all of the crappy wrappers
Im looking to use the most popular wrapper because that will be the one to get the fastest support with in this server
yea
other people dident even have a clue there was other wrappers
And now no one really know's which wrapper to use
Im waiting to see what carl-bot uses betting PyCord / Hi
idk if i'm just dumb but tf is with these docs on @bot.slash_command for pycord
what even are the kwargs
theres many
and where do i see them
just like if you were making a d.py command
but it doesn't work with commands.slash_command?
meaning that they won't work in cogs
🤦♂️
classic forks
PyCord does not support cogs atm
they’re all pretty much bad
ikr
¯_(ツ)_/¯
Would you like to explain which one is good to use then?
Danny stoped maintaining it
there's still some new stuff that discord wants to add and since dpy stopped development it won't have those things
for now
Im not making a bot growing it than a week later having to recode the whole bot using a new wrapper
not fun
that’s when you come in and update the wrapper yourself
like everyone could, some in this help channel don't even know basic python
learning is always an option
Not fun either
Thats why PyCord And Disnake are here
yeah nothing is fun
ask, do not ask to ask
ok
anyways i will be using pycord
look
because less than a week tell pycord gets cogs
Kek account generator bot 🤣
yes
i host bot and work
but if host replit and glitch or another hosting
have proplem
then dont use them
Becuase folder named Accounts is missing
wait
Same with fortnite.txt
Jesus its in the error
is not fortnite
is all files
in folder
accounts
bangs head I give up
lets just take a chill out quickly
this is a linux runtime
you sou want to use forward slashes
secondly
this bot looks very sketchy in terms of what it seems to do 
yes
what?
If your bot is a default command -> response, you should use a standard http framework and slash commands
Unless your bot absolutely needs the message intent you wont be getting the intent
okay, so, no
we're not going to help with that
because that breaks all sorts of Terms of service
both of Discord's and most likely the service you're creating account for
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
generate numbers
that doesnt matter
???
is number
but you just said it is

you just said it was
wait i send code
secondly, just because it's random numbers
doesnt make it not tos breaking
Discord will ban you if you generate nitro links via random numbers or not
and this policy goes for any account generation
so no, we're not going to help with that.
bruh
the funny thing is, that generating random account keys never ever works
Can someone help me understand how I should be doing my wait_for's? I have this command massban2 which takes a greedy input of discord members that need to get banned. I want to make the bot then ask me to add a reaction for if I want to add a ban reason. If I click ✅ then I want it to wait for a msg and save that msg to a variable. If I were to react with a ❎ tho then I want the bot to use a default reason. How close am I to getting this working and where might I be going wrong? ```py
@commands.command(description = "Lets moderators mass ban members.", usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban2(self, ctx, targets: commands.Greedy[discord.Member]):
with ctx.channel.typing():
confirmation = await ctx.reply(f"You are about to ban {len(targets)} members. Do you want to add a reason for this ban? If yes react with ✅ and if no react with ❎")
await confirmation.add_reaction("✅")
await confirmation.add_reaction("❎")
def check(reaction, user):
return user == message.author and str(reaction.emoji) == "❎" or "✅"
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout = 60.0, check = check)
reason = self.bot.wait_for()
except asyncio.TimeoutError:
confirmation.edit("The time to add a reaction timed out so the defualt reason of `Unspecified` will be used")
reason = "Unspecified"
else:
reason = await client.wait_for('message')
for user in targets:
await user.ban(reason = reason, delete_message_days = 0
await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")```
return user == message.author and str(reaction.emoji) == "❎" or "✅"
You have a problem with or here
you must have a full condition on both sides of the logical operator
Also ```py
reason = self.bot.wait_for()
... str(reaction.emoji) == ":negative_squared_cross_mark:" or str(reaction.emoji) == ":white_check_mark:"
Umm No.. 
O.o
It's just discord markdown to write emojis like that, comparing unicodes will work fine
would it be better to do a if statement than this function for the check?
Make it a set and check if the emoji is in or not ```py
str(reaction.emoji) in {"❎", "✅"}
!e ```py
x = 1
print(bool(x == 2 or 3))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
True
Should not be true, but it is ^
okay how's this looking?```py
@commands.command(description = "Lets moderators mass ban members.", usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban2(self, ctx, targets: commands.Greedy[discord.Member], delete_days: Optional[int] = 0):
with ctx.channel.typing():
#reason = reason or "Unspecified"
confirmation = await ctx.reply(f"You are about to ban {len(targets)} members. Do you want to add a reason for this ban? If yes react with ✅ and if no react with ❎")
await confirmation.add_reaction("✅")
await confirmation.add_reaction("❎")
def check(reaction, user):
return user == message.author and str(reaction.emoji) in {"❎", "✅"}
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout = 60.0, check = check)
reason = await self.bot.wait_for('message')
except asyncio.TimeoutError:
confirmation.edit("The time to add a reaction timed out so the defualt reason of `Unspecified` will be used")
reason = "Unspecified"
for user in targets:
await user.ban(reason = reason, delete_message_days = delete_days)
await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")```Is this actually saying that if the reaction is ✅ then wait for the user msg but if it's ❎ then set a default value? or do I still need to do that
you still need to do that
you aren't checking which reaction they reacted to
so use if statements to check it
Try it and see
... reason = await self.bot.wait_for('message') reason will be a Message object not a string, await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")
Does anyone khnow a code that massiverole evryone
so do reason.content instead of reason
wdym by "massiverole"
give a specific role to everyone in the server?
Like i'm tired of trying i want to make a command that gives a role a specific role to everyone
"gives a role a specific role to everyone"..?
show what you have
lol
Like
could I not do reason = await self.bot.wait_for('message.content ')? not sure if i'm gonna need this reason as a msg object again altho I might chnage that in future
nah, wait_for takes events
It gives Everyone the role mentioned by the user 
wait_for accepts events, like on_message, on_reaction_add and more, but just without on_
ik but what have you tried so far, send the code
ah okay
I searched but i didnt find like i need some syntax ton khnow how to do it (i dont have the code right khnow lol)
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.
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, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
I'm new at python bot coding
Thx
loop over all the members in the guild and give the role to it using what @slate swan linked
remove the bots and owners from it
loop over all the members in the guild
any other way? i can only think of that rn lmao
ratelimit headers coming

thats why give the role to the member when they join the guild
Yeah depends tbh, you can sleep the command every few seconds and use max_concurrency to prevent rate limits
But still not a good idea with a few thousand members
Another question can we like by a chance change the prefix of a bot with a command and without a database
without a database.. maybe
Because i was searching didnt find how to do it
All the tutorials persons said you need a database
you need some kind of storage to save the prefixes, and database is the only option. don't think about json
We can do a database in our pc or i need to buy a vps or anything else
If you can keep your pc turn on 24/7, sure
Okay this is what I have so far. I decided to also make a input for the amount of days of messages to delete. Have I got any obvious (or less obvious) mistakes? https://sourceb.in/rnsjT6mp3w
@bot.command()
@commands.has_permissions(manage_roles = True)
async def mute(ctx, user : discord.Member,*,reason= "No reason provided idot"):
roleobject = discord.utils.get(ctx.message.guild.roles, id=870577969477857289)
await user.add_roles(roleobject)
await user.send("You have been muted in **Aurora | Social • Icons • Anime** because:"+reason)
await ctx.send(f":white_check_mark: {user} was muted")
i can nopt for the life of me figure out how to code a timed mute. but this is what i have so far
is it giving you any errors?
U could save unmute datetime in db, then make a task to check if current date is later than members unmute date, and if it us, unmute him
That way it works even if bot goes offline for a but
Bit
The problem w it is that it wont unmute on exact unmute date, it will have a bit of delay
also would could just use py await user.send("You have been muted in **{ctx.guild}** because:"+reason)orpy await user.send(f"You have been muted in **{ctx.guild}** because: {reason}")
i want to avoid a db though
U could use json then
thats what im thinking
Make it an actual f-string, and put reason into it too
Or just asyncio.sleep but tgat would notvwork with longer periods of time
Best option is w db
Or json
Don't use json files for databases
#discord-bots message
done
Yes but for his use case u could use it
Show code that is giving u error
embed = discord.Embed(title="You leveled up!", description=f"You are now level **{level}**", colour=0x00FF00)
embed.set_thumbnail(url=helper.avatar_url)
file=File(buffer,"rank.png")
embed.set_image(url="attachment://rank.png")
await helper.dm_channel.send(embed=embed,file=file)
Whats helper
a member object
Can anyone see where i'm going wrong?py ERROR:cogs.error_handler:TypeError: edit() takes 1 positional argument but 2 were given (In massban2) Traceback: File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/moderation.py", line 363, in massban2 confirmation.edit(f"You are about to ban {len(targets)} members. Do you want to select how mnay days of the members messages get deleted? If **yes** react with ✅ and if **no** react with âŽ")my code: https://sourceb.in/lqMvejLjMY
nm it does
? U sure
it does
Can u just send the part that is giving u error in codeblock
Try it
same thing happens
Send error in codeblock
edit takes only kwargs. If you want to edit the content of the message, use the content kwarg
I’ m on mobile, It’ s hard to see there
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 209, in invoke
return await self.func(self.cog, *args, **kwargs)
File "c:\Users\pc\Desktop\Projects\OCR-School\cogs\help.py", line 33, in exp
await self.addExp(member, amount, ctx.guild, False)
File "c:\Users\pc\Desktop\Projects\OCR-School\cogs\help.py", line 361, in addExp
await helper.send(embed=embed,file=file)
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\dpy_overrides.py", line 323, in send_override
return await send(channel, *args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\dpy_overrides.py", line 264, in send
data = await state.http.send_files(
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 185, in request
async with self.__session.request(method, url, **kwargs) as r:
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 343, in request
return _RequestContextManager(self._request(method, url, **kwargs))
TypeError: _request() got an unexpected keyword argument 'form'
well the error handler thinks it's thispy confirmation.edit(f"You are about to ban {len(targets)} members. Do you want to select how mnay days of the members messages get deleted? If **yes** react with ✅ and if **no** react with âŽ")
Make the strink keyword argument
so confirmation.edit(content = "My str"
👍
content=if you are boutta ban…
Send help.py line 323
Well my codes too long to send here so you can find it here: https://sourceb.in/2mfsV5IOdS. I'm having an issue where the bot is listening to my input for the reason but is not prompting me to input the num of days i'd like to delete and I'm not sure why
why is it doing this?
code
@client.command()
async def poll(ctx, *, question=None):
if question == None:
await ctx.send("Please write a poll!")
icon_url = ctx.author.avatar_url
pollEmbed = discord.Embed(title = "New Poll!", description = f"{question}")
pollEmbed.set_footer(text = f"Poll given by {ctx.author}", icon_url = ctx.author.avatar_url)
pollEmbed.timestamp = ctx.message.created_at
await ctx.message.delete()
poll_msg = await ctx.send(embed = pollEmbed)
await poll_msg.add_reaction("⬆️")
await poll_msg.add_reaction("⬇️")```
how dynamic is those fancy looking embeds with built in buttons? would it be possible to use them to make games with a join system for each round?
Hello how do make the bot say a message instead of this error
I've tried this python elif isinstance (voiceChannel is None): await ctx.send("You not in vc kid") return and many others but they didn't work
you should return if question == None
return await ctx.send("Please write a poll")
btw i'm not using anything against discord tos, just a program that plays local files
Thanks
👍
can someone link me the doc for the channel argument thing
e.g. async def test(ctx, channel:discord.Channel):
hi i've implemented a cooldown for my bot but i need it to send a message if CommandOnCooldown is triggered
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title="error",
description="run again in {round(error.retry_after, 1)} seconds",
color=0xE02B2B
)
await ctx.send(embed=embed)
is this good?
does anyone have any idea as to why bot.user returns None?
Did u come here w code asking if it will work b4 running it…
it doesn't work lol
returns this
instead of sending the embed
hold on lemme add the commas
Which line of code makes it return this
this
Are u using logging library?
um no
Then what prints that out in console
idk
Run the debugger
ok
Set a breakpoint in the command that causes this error
guess i can just use bot.waituntilready
uh
man i love discord.py :(
I think u tryna run 2 flask servers on same port
hmm
i don't got a cog
oh.
Show command
lol
@client.event
async def on_message_delete(message):
client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
@client.command()
async def snipe(ctx):
try:
contents, author, channel_name, time = client.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("No message was deleted!")
return
embed = discord.Embed(description=contents, color = discord.Colour.purple(), timestamp=time)
embed.set_author(name=f'{author.name}', icon_url=author.avatar_url)
embed.set_footer(text="caught in 4k")
await ctx.channel.send(embed=embed)
client.sniped_messages = {}
Did u put snipe command inside on_message_delete?
i'm confused on what you are asking
this is at the top
and this is the code
they are in 2 seperate places
what i mean by my function at the top
Try commenting out the event and see if u get same error
doing the command you mean?
Yes
k lemme get to my test server
It may be that event fucked a little w ur commands
Does anyone khnow how to blacklist a member from the multiple servers that the bots are in
k i still get the same error
what did you do with ur client variable there
Wym blacklist
delete the
client = discord.Client()
first
arn't vars supposed to be at the top
you still reassign it next line, and it would still be completely wrong
ye i got bot = commands.Bot()
no you don't
Where?
lul
Remove client = discord.Client bs, u dont need it
bot = commands.Bot(command_prefix="your_prefix", help_command=None)
use bot
wrong
its not wrong essentially, but using the bot as the variable is better practice since discord.Client() is a thing.
^
amjsdbajkefbnaselfbaskfgaseg
Lmfao
there's supposed to be a replace everything thingy in your IDE...
Naming is one of most important things in coding, make sure u get it right at the start or u gonna have to fuck w it later
youtube tutorials
alot of this server uses client
But bot is correct
the thing is, client is not made for command usages
Yea
how to i replace everything that was client into bot
What ide u using?
VS Code on top
vsc
Idk shortcut for that one
select a client in your code, click on replace every o... something and type bot
It’ s shift + f6 in pycharm
lemme check
man
you select something
U got the code tho
yeah but he not updating
ok yay
Yea, if something breaks u gotta update urself
it changed it
asyncio.run(bot.wait_until_ready())
File "D:\Python 3.9.1\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "D:\Python 3.9.1\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "D:\Python 3.9.1\lib\site-packages\discord\client.py", line 890, in wait_until_ready
await self._ready.wait()
File "D:\Python 3.9.1\lib\asyncio\locks.py", line 226, in wait
await fut
RuntimeError: Task <Task pending name='Task-1' coro=<Client.wait_until_ready() running at D:\Python 3.9.1\lib\site-packages\discord\client.py:890> cb=[_run_until_complete_cb() at D:\Python 3.9.1\lib\asyncio\base_events.py:184]> got Future <Future pending> attached to a different loop
now i get this error when using bot.wait_until_ready() (I am not too well versed in asycnio)
still get the same error with Command "snipe" not found
didn't check it out, but this was the first thing that I found
and it had a reply with a tick

complicated solution, good luck mate
@lone lichen
the snipe command code?
yes
i have a function at the top
interesting
do you need my function?
two on_ready events
ye
just put the content of your second one to the first one
and delete the second one
you can't have two of the same events
ty! might go to the guys in #async-and-concurrency for some help lol cause my brain dies when it comes to async
lol
k done
this is saying that the command isn't found
but ill try
nice
it still gives me a error
akefbnjkfbadskgbaslkgsarg
Show new code
i saw your code before and the snipe command was inside the on_message_delete event
that’s the issue
now it's not
then did it work?
did you save your code
stop spamming lmao
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.pydis.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.




