#discord-bots
1 messages Β· Page 275 of 1
it's isinstance
it worked, thanks man
Nice, gl
oh yeah why did i look at this line and not function def
The question is why didn't that if work
the other question is why in else you assign id as guild object
if its not guild i would just return or raise
Debug π
you dont pass guild object to the function
print(isinstance(guild, discord.Guild), guild) is what i'd do first
to see that it actually doesn't work
print(isinstance(guild, discord.Guild), guild)
^^^^^
NameError: name 'guild' is not defined```
Has to be in the scope of the function.
where did you put it
so?
put it at the top
The error will come faster
Well this is interesting
Guild is a Hashable class, meaning when imported it's not identical when imported in init.
isinstance(guild, discord.guild.Guild) Would most likely work.
So?
isinstance(guild, discord.Guild) works fine by me
but the type of guild is <class 'discord.guild.Guild'>
one line above
outside if
inside function
What's the point of isinstance(guild, discord.Guild)? Shouldn't it always be a discord.Guild?
Is what I would expect...
That's why I'm asking for help because I don't understand the database and discord py

Sorry
I wouldn't recommend MongoDB for a Python project anyways xd
Mongo is great for js and ts tough.
Eh, it's more about the nature of the data you're be dealing with rather than the language if you ask me
Yeah could get behind that.
I think Discord fundamentally lends itself well to a relational database format, so still, I'd recommend SQL over NoSQL when working with Discord-related stuff
That really depends on the bots size tough.
I am getting that error after running this code ```py
@bot.command(aliases=['Casino', 'ΠΊΠ°Π·ΠΈΠ½ΠΎ', 'ΠΠ°Π·ΠΈΠ½ΠΎ'])
async def casino(ctx, count=None):
user = check_user(ctx.author.id, ctx.guild)
if not count:
return
try:
count = int(count)
except ValueError:
await ctx.send(embed=discord.Embed(title="ΠΡΠΈΠ±ΠΊΠ°", description="ΠΠ΅ΠΊΠΎΡΡΠ΅ΠΊΡΠ½ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ ΡΡΠ°Π²ΠΊΠΈ", color=discord.Color.red()))
return
currency = get_currency(ctx.guild)
if count >= 10:
if user['balance'] - count >= 0:
times = user.get('times', {})
last_beer_time = times.get('beer', dt.utcnow() - timedelta(seconds=600))
total_seconds = (dt.utcnow() - last_beer_time).total_seconds()
rand = random.randint(1 if total_seconds < 600 else 10, 100)
if rand <= 77:
rand = -1
elif rand > 77 and rand <= 92:
rand = 2
elif rand > 92 and rand <= 99:
rand = 3
elif rand > 99:
rand = 10```
Maybe it will give something
what is the error
.
that is the code, not an error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidDocument: cannot encode object: <Guild id=1065340260957044797 name='Ukraine Community' shard_id=0 chunked=False member_count=4>, of type: <class 'discord.guild.Guild'
Is a way to use a loop but using time instead of a countdown?
Do you want it to run at that specified time each day?
Yeah
The tasks.loop decorator has a time= kwarg
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
i've used both and agree, though I've found some use cases for NoSQL with bots, but I'm not a huge fan of the motor package
(a client specifically requested I use mongodb) and I think other bot makers don't like it either
might swap it out with aiohttp + mongo data api if I can be bothered
using the get_guild function of discord.Client is the only was to get discord.Guild from a guild id right?
I don't know about "only" but it's the simplest and most straightforward
And if you want to get a guild from ID that's the method you should use
yeah but I am not in the file where I made the client. I doesn't work by importing client ofc.
Where are you in?
I made a separate file to make some useful function. I need to get guild in that file
You should pass the guild into the function then
If you're passing in ID, it shouldn't be much harder to pass in a guild
it's a bit complicated, I will try to explain simply.
there is a function I am working on and there is another function which returns some data from an sql file about a guild. but that function takes guild object instead of Id and I have to use that function in the function I am working on.
a bit messy but yes I need guild object from id
I can do that but that for my code I will have to change a few things.
also @sick birch when did you start working on discord.py lib
What do you mean?
I haven't really "worked" on discord.py, I've only contributed some examples
But I do work with discord.py quite a bit
yes, I am sorry, with I mean
idk it's been a while I am using this and still there are things that are completely out of my mind
a few years at this point
maybe it's my first library of first language I learned
oh alr
But this is more general Python stuff rather than discord.py specific stuff
that's cool
But to answer your question - you need to pass around the client object wherever you need it, as arguments to functions
yeah okay, I am not even coding right now so I will try it later
!d discord.Client.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Thank you
my code was working fine last night but now i cant even import
error: ImportError: cannot import name 'commands' from 'discord' (C:\Users\wodgenzi_\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
i tired re installing discord.py
You are magician if it was working
Because that errors says truth - there is no commands inside discord
It is in discord.ext

i reinstalled visual studio code and its fixed now
the from discord import commands is working?
and yeah its like this since forever
its not from dsicord import commands
**error: ImportError: cannot import name 'commands' from 'discord' **
!e from numpy import something
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | from numpy import something
004 | ImportError: cannot import name 'something' from 'numpy' (/snekbox/user_base/lib/python3.11/site-packages/numpy/__init__.py)
i dont have previous error message cuz new IDE
otherwise i would have checked the exact error
but you literally send this one?
you had to got this from somewhere
by exact error i mean
the whole text, not just the last time error name
full traceback wouldnt actually change anthing
this import wouldnt occur in source code
the error was in this file and these are the import lines, idk man
I'd believe it was not saved
We could say exactly that it's not in that code
yes maybe, i thought that too but i am pretty sure that i made no changes
i assuming a change got reverted by reinstalling IDE, how that happened? i dont know
if you didnt save a file could be
but i belive when closing ide it should warn you that you have unsaved changes
there are many files, possible
well, surprisingly i just tried and it didnt warn
what ide?
like it shows this dot when unsaved and i am closing it and its not giving a warn
visual studio
based on screenshot visual studio code
thats why i use autosave
it has a built-in or extension?
that it wont save on each character you type
but after a little break of typing
in simple terms
this?
yeah
i dont know whats the normal mode but anyway i am still disabling it
you might notice that when you open a file it shows up with cursive name
and when you type something in it is in normal text
the cursive is preview
oh, yeah
found it
enabled cause i dont code on windows π€
im not using linux either
macos
is it any better while coding or just as same as windows?
If you're on windows and want to get a taste of linux you could try out wsl
damn
i have used linux for like a week and it was good
anyone know how can i pass the client variable to another file?
if i make the class a cog then functions in it will become useable by discord users.
the functions where i need client variable are just for my use in code. they are used to fetch data from data base
Why would they become useable by users?
Only commands will.
But yeah, for custom functions you can use just a normal class/functions, no need a cog
yeah sorry my bad there, still is it the right way for what i am doing?
Just pass the bot in its constructor/arguments. Same as for cogs
^
def my_function(bot):
...
my_function(bot)
or
class MyClass:
def __init__(self, bot):
self.bot = bot
... = MyClass(bot)
or something else, depends on how you want it to be
sorry didnt know that it wont be commands
yeah i am trying the second one
well i was a bit wrong there, there are not commands.
i just noticed, a function in a class was working fine without the self parameter, anyone know how that happened?
You didn't make an instance maybe
Or you did make it static but i guess you didn't
^
oh, like i didnt add the brackets while using?
like that
i guess, i am gonna take another python course then start again
i have some uncleared concepts about async, decorators and OOPs
wow
i don't often see such people here
usually here are "i have no idea what i am doing i will just do something random and keep asking"
its just i learned python from an indian guy on youtube, now i saw there are harvard CS50 lectures too
i knew what i was doing but like
i didnt know how that was happening
and thats kinda frustrating when errors pop up
Not that the Harvard lectures are hard lmao
They go in to depth too much for my taste
Why when I put more than one argument in command it only reads the first one and when I run the command it's telling me that missing assignments that I already put them
Please any on help me
I tried with and without the star
And it's the same
async def bc(ctx, member, message,* ,user: discord.Member):
async def bc(ctx, member, message, user: discord.Member):
And how are you calling it?
hah?
show it exactly
.bc hello
You are asking for member, message and user
Here you gave only one argument member
I will show you the command code
@bot.command()
async def bc(ctx, member, message, user: discord.Member):
guild = ctx.guild()
count = 0
for member in guild.memebrs:
if member.bot:
pass
elif member.status is not discord.Status.offline:
try:
await user.send(message)
count += 1
except:
pass
else:
pass
embed = discord.Embed(title="Brodcast", description="Brodcast info")
embed.add_field(name="Messages", value=count)
await ctx.reply(embed=embed)

What
Looks like you don't understand what you are doing :/
Why
Calling attribute with brackets, Adding multiple pass and conditions that are doing absolutely nothing, Calling with one argument and expecting to get 3
What are member and message for? You are not using them. And you aren't giving
Did you understand what the command is doing?
Spamming online people
if member.bot?
message for set the message to send
Ye. Actually it has some use, but if you don't do something inside if just change the second condition
Also
else:
pass
That surely does nothing
So I will remove
ye, sorry, didn't see
but member not. you are overwriting it without using
and it's strange that you are looping over member and then sending all to the one user
You didn't answer me
I guess you want to keep only message
@bot.command()
async def bc(ctx, message):
And send message not to the same user, but to each member once
await member.send(message)
It's not the code you pasted.
._.
It's saying about line user = discord.Member()
You don't have such here
Yup I add it
But you have guild = ctx.guild() which is also wrong
It's not a method, just an attribute. No need to call it
I will try something and show you
@bot.command()
async def bc(ctx, message):
message = discord.Message()
count = 0
for member in guild.memebrs:
if member.bot:
pass
elif member.status is not discord.Status.offline:
try:
await member.send(message)
count += 1
except:
pass
else:
pass
embed = discord.Embed(title="Brodcast", description="Brodcast info")
embed.add_field(name="Messages", value=count)
await ctx.reply(embed=embed)
correct?
remove message = discord.Message()
I forgot
add guild = ctx.guild or change loop to for member in ctx.guild.members:
I know it wrong
I have I question
Can I replace
ctx.guild with guild id?
Ok
bot.command()
async def bc(ctx, message):
count = 0
for member in guild.memebrs:
if member.bot:
pass
elif member.status is not discord.Status.offline:
try:
await member.send(message)
count += 1
except:
pass
else:
pass
embed = discord.Embed(title="Brodcast", description="Brodcast info")
embed.add_field(name="Messages", value=count)
await ctx.reply(embed=embed)
```
Guild = discord.get_guild()
And Id in ()
Not discord
What
It's not discord method
.
There is a change
ctx.guild.mebers
In for
Like you said
!d discord.ui.button
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
just pass emoji argument
...
can choices have space in ther text??? like ai model space between ai and model
Just try it
It means exactly what it says, 429 Too Many Requests
You're probably spamming something to the API
This thing only on repl it
Replit
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
(from #965291480992321536 )
The last one is your case
Eh, I don't think so; looking at their code
bot.command()
async def bc(ctx, message):
count = 0
for member in guild.memebrs:
if member.bot:
pass
elif member.status is not discord.Status.offline:
try:
await member.send(message)
count += 1
except:
pass
else:
pass
embed = discord.Embed(title="Brodcast", description="Brodcast info")
embed.add_field(name="Messages", value=count)
await ctx.reply(embed=embed)
```
> [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/)
It's most likely because they're sending messages to every member of a guild
I amtrying to make a levelling system. Here's my code:
@client.event
async def on_message(message):
print(message.author.id)
user = message.author.name
if message.author.bot:
print("Nevermind guys!")
return
else:
await message.channel.send(user)
async with aiosqlite.connect("stuff.db") as db:
async with db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER UNIQUE, guild INTEGER UNIQUE, xp INTEGER, level INTEGER)")
await cursor.execute("INSERT OR IGNORE INTO users (id, guild, xp, level) VALUES (?, ?, ?, ?)", (message.author.id, message.guild.id, 1, 1))
if cursor.rowcount == 0:
await cursor.execute("UPDATE users SET xp = xp + 1 WHERE id = ? AND guild = ?", (message.author.id, message.guild.id))
await db.commit()
await cursor.execute("SELECT xp, level FROM users WHERE id = ? AND guild = ?", (message.author.id, message.guild.id))
row = await cursor.fetchone()
xp = row[0]
level = row[1]
exp = 5 * level**2 + 10 * level + 100
new_level = int(math.sqrt(xp / 5 + 10) - 1)
if new_level > level:
await message.channel.send("Level Time!")
level = new_level
await cursor.execute("INSERT OR IGNORE INTO users (id, guild, xp, level) VALUES (?, ?, ?, ?)", (message.author.id, message.guild.id, xp, new_level))
print(level)
await db.commit()
if message.content == "c!hello":
await message.channel.send("Hello. Hope all is well.")
When I run it there are no errors but it isnt properly updating the table:
Ive uploaded an image:
as u can see its alternating between 1 and 2 for the level and nothing changes with xp. Please help! whats wrong. HELP!
I haven't figured out what exactly is wrong with that thing yet but here are some recommendations
- You should only have one connection for bot. Example
class MyBot(commands.Bot):
db: aiosqlite.Connection | None
async def setup_hook(self):
self.db = await aiosqlite.connect(...)
async def close(self):
await self.db.close()
await super().close()
- Execute scripts for creating tables on setup stage, not when you need to access db
- I'm not aiosqlite expert but creating additional cursor seems obsolete, there's
db.execute()
And I do think you confused var names in this block
xp = row[0]
level = row[1]
exp = 5 * level**2 + 10 * level + 100
new_level = int(math.sqrt(xp / 5 + 10) - 1)
Cause your exp variable is unused
Maybe you meant to use exp in new_level calculation
- don't do commands in
on_message, use commands framework
i cant
because it wont pick that up
Pick what up
A question shouldn't the new_level be level+1?
I don't think so
he's calculating the level according to the exp he has
wait I just understood what you meant
Yeah see
yeah you're right
I don't see level being incremented
And i don't know what kind of dish is that new_level cooking
Like if the level that is retrieved in level variable is one so doesn't it need to be incremented?
I think it doesn't
you have 100 xp
and talk and get 105xp, which is level 2
100xp -> Level 1
105xp Level 2
if you have more or equal than 105xp, the new_level would be 2
so level < new_leve would be true
Tbh i still didn't get it
Like as far as i can see the new_level is calculated based on current xp
Level 1: 1 xp
Level 2: 2xp
Level 3: 4xp
Level 4: 8xp
you are on level 3, and have 5 xp
when you talk and get 3 more xp
your last level (level) will be 3, but the new_level calculated with the past xp would be 4
So yeah how will the this 4 be changed in the db
wdym
Like i don't know how that formula is working
!e
import math
lvl=int(math.sqrt(100/5+10)-1)
print(lvl)
@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.
4
So 100 xp is equal to lvl 4
!e
import math
lvl=int(math.sqrt(160/5+10)-1)
print(lvl)```
@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.
5
tbh I would make a table for each level and xp needed
Math scales a lot better.
Welp i would calculate the xp till next level and define it and then check the current xp with that
And when the user levels up increment the level by 1
yeah but I don't think noone will get to that level
Wouldn't that put a cap on levels
Like the bot will only assign levels till u told it
Yep.
!e
import math
lvl=int(math.sqrt(1000000/5+10)-1)
print(lvl)```
@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.
446
Well if you're going to make a table then I'd do till a certain level like 100 and then make it static like 20000xp for next level, but then again math also allows for that curvage.
!e
lvl=1
xp=15
xp_next=lvl*10
if xp>xp_next:
lvl += 1
print('level up')
print(lvl)
else:
print('XD')
@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | level up
002 | 2
Welp i use this approach
I remember doing math for slots command in bobux π©
I mean exponential equations are great for xp systems.
how could I get a guild id in redis
you will need to elaborate
async def my_function_that_gets_id_from_redis():
# your code
await my_function_that_gets_id_from_redis()

so like
r = redis
@tasks.loop(time=time)
async def fotd():
channel = r.get(f"channel{guild.id}"
``` this wouldnt work so what do I do
Could i use fotd(guild):?
<@&831776746206265384>
@lavish vortex
here
@runic pond

!ban 862434693232197654 That sort of language is not allowed here.
:incoming_envelope: :ok_hand: applied ban to @dry dust permanently.
idk
i don't use redis
i didn't understand what you are trying to do
in a task loop I want to get a guild thats in the db but It wont know what guild im talking about
If you don't know what guild do you want, what do you want to get?
hello so i have this code
videos = pytube.Search(song_title).results
if not videos:
await interaction.response.send_message("No search results found for the given song title.")
return
video = videos[0]
audio_stream = video.streams.filter(only_audio=True).order_by('abr').last()
audio_file = audio_stream.download()
if interaction.user.voice is None:
await interaction.response.send_message("You need to be in a voice channel to use this command.")
await interaction.response.send_message(f"Now playing **{song_title}**")
vc = await interaction.user.voice.channel.connect()
vc.play(discord.FFmpegPCMAudio(audio_file))
playback_event.set()
await playback_event.wait()```
and i get the error
```error
await interaction.response.send_message(f"Now playing **{song_title}**")
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
defer it
? how
your interaction
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
We cant help you
its ffmpeg
i just use it in my server
Doesnt matter
oh
i have youtube premium
So?
i pay for youtube
not gonna do anything
Nope
bruh moment
Its against YouTube tos
what about spotifiy
Same
do they care?
oh ok
cuz i can play why wont you adopt me from dahr man
Maybe they have permission from YouTube 
hmm dont think youtube does that
They have some paid api i believe
But you cant use it for a discord bot
how do i use spotify thing for music ? anyone got some information on a tutorial or anything ?
well guess everyone goes against spotify their terms and conditions
Create own music service π₯Ά
hi guys, I just wondered if you knew some servers to advertise our discord bots, because it's actually hard to get people interested about the bot... thanks
have an original idea
original idea be like:
they were original ideas when they launched
Discord bots are very saturated tbh
It's difficult to create a popular one now-a-days
first time making a music bot
also first time making a bot with python
worth it ngl

yeah you're right
yeah I already saw this, thanks btw
async def play_music(self):
print("play_music method called.")
if len(self.music_queue) > 0:
print("it is over 0")
self.is_playing = True
print("it is true")
voice_channel = self.music_queue[0][1]
m_url = self.music_queue[0][0]['source']
print(m_url)
self.music_queue.pop(0)
if self.vc is None or not self.vc.is_connected() or self.vc.channel != voice_channel:
print("awaiting voice_channel.connect")
try:
self.vc = await voice_channel.connect()
except Exception as e:
print(f"Failed to connect to voice channel: {e}")
print("URL of song: ", m_url) # Debug
try:
self.vc.play(discord.FFmpegPCMAudio(
executable="C:\\Users\\starf\\PycharmProjects\\AudioAnalyser\\venv\\Lib\\site-packages\\imageio_ffmpeg\\binaries\\ffmpeg-win32-v4.2.2.exe",
source=m_url))
except Exception as e:
print(f"Exception occurred while playing music in play_music method: {str(e)}")
while self.vc.is_playing():
await asyncio.sleep(1)
# If more, play next
if len(self.music_queue) > 0:
self.is_playing = False
await self.play_music()
# If no more, disconnect
else:
self.is_playing = False
await self.vc.disconnect()
else:
print("is not playing")
self.is_playing = False```
impossible. it stops working at
```py
try:
self.vc = await voice_channel.connect()
except Exception as e:
print(f"Failed to connect to voice channel: {e}")```
its like it has no idea that the bot IS connected to a channel. im going insane on this. any insight?
im trying to print elements out of a list with slash commands but when i print it with a loop it only prints the first element of the list
async def view(interaction = discord.Interaction):
if len(homework) > 0:
for x in range(len(homework)):
await interaction.response.send_message(f'{homework[x]}: {homework_notes[x]}')```
how do i get it to print all the elements
You can only use the InteractionResponse.send_message once
If you need to send more than one message, use interaction.followup.send instead
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
ok
(by the way, if the homework variable is a list, you can just iterate through it)
!e
a = ["cat", "meow"]
for b in a:
print(b)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | cat
002 | meow
example?
so do i use that to send everything or just the first message
How do i check if on_message has image or video in it?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Check if this is empty or not
If you need to send more than one message, use
interaction.followup.sendinstead
π€·
so like
interaction.response.send_message can only be used once, interaction.followup.send can be used multiple times
await interaction.followup.send('stuff')
if message.attachments == None:
This way?
!e
print([] == None)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
No
Then?
!e
if []:
print(0)
if [0]:
print(1)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e
test = []
test.append("hello")
@blazing girder :warning: Your 3.11 eval job has completed with return code 0.
[No output]
:c
!e
test = []
test.append("hello")
print(test)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
['hello']
Happens a lot lmao
weird , if i i do it on my discord bot to save last message a user typed i get an error thats its Read only
do you know why?
Can I see the code?
oh
it's supposed to be user_history.append(zumsagen)
ohhh damn
not user_history.append = (zumsagen)
oh shit now i see
didnt notice that there ngl
looked normal to me xd
thx for the help :3
Because your settings
Woah there's settings for this?
Yes?
how to make discord.py send avatar image (not sending url but send image)
Or you can just escape it with backslash
i need code
:)
π
I've been doing this for whole time lmao
Ah shit now I see
I didn't know this setting existed 
:)
WOAH
life changing
frfr
is there a difference
between
test = [] and test = {}
?
help pls
[] is a list and {} is a dictionary
!d discord.Asset.to_file
await to_file(*, filename=..., description=None, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Converts the asset into a [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").
New in version 2.0.
or a set afaik
how to get the user avatar? from mention
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
no, mention and download avatar then send the image (not url)
What URL?
I don't see any mention of an URL here
user.avatar.to_file()
That's what it is
thx bro
if message.content == '!avatar':
clientProfilePicture = message.author.avatar.to_file
await message.channel.send(clientProfilePicture)
good?
No
to_file is a function, that returns a coroutine, which you need to await
And it returns a discord.File object, which should be passed into the file or files argument of the send method
i need the full code i dont understand π
Learn python before making bots Β―_(γ)_/Β―
btw I didn't know that
I've always done something like
response = requests.get(user.avatar.url)
filepath = avatar_hash + '.png'
with open(filepath, 'wb') as f:
f.write(response.content)
await message.channel.send(file=discord.File(filepath))
requests π
Saving file locally :p
Here it's better to use methods from dpy, but fyi there is
!d io.BytesIO (same as file but in memory)
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
So, I could've just done discord.File(io.BytesIO(response.content))?
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
ok it can't
to_file() need to to awaited
Oh I see
Should it go like await messagable.send(file=await user.avatar.to_file())?
Python is like "There's always a better alternative, only if you know."
You always can convert it by yourself
by yourself :)
true
i haven't seen any
i can use chatgpt ig π
You mean as a command argument?
yea
do you know how to do it without converting it yourself
There's stuff like datetime.strptime or you can make a commands.Converter and parse it yourself I guess
Instead of searching for ready one you could already write it
It is just two lines of code
ok
!d datetime.datetime.strptime
classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.
If *format* does not contain microseconds or timezone information, this is equivalent to:
```py
datetime(*(time.strptime(date_string, format)[0:6]))
``` [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format canβt be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime "time.strptime") or if it returns a value which isnβt a time tuple. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.fromisoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat "datetime.datetime.fromisoformat").
k ty ive never used datetime lol
okay... this is getting so annoying. anyone know why this doesnt work?
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
print("Attempting to join voice channel...")
await channel.connect()
print("Joined voice channel successfully!")
else:
await ctx.send()```
```lsd2#0 .join 1133330391730765854
Attempting to join voice channel...```
this is my console output. makes no sense, all it is supposed to do is join a channel.
But it shows as there...
did you write this code?
Yes i just wrote it right now
oh thats odd since the pass_context argument doesnt exist for like 2 years its outdated
i saw it on a tutorial since ive been trying to get my bot to join for like 5 hours
ive tried so many things. do you know the problem? ive given my bot admin, every permission, a custom role with only speak enabled.
cannot for the life of me get it to work
Which tutorial
Shouldnt this code work regardless
ive done many different attempts
all of them stop at await join.
Yeah found this tutorial.
same exact code basically
using a youtube tutorial is the worst idea to make a discord bot
Then tell me what to use
ive gone to github to find some code
all the same, ctx.message.author.voice.channel.join
gone on forums all the same
thats why im asking for help.
the VoiceChannel does not have join method
connect i mean
told you ive been up all night im tired and just need a staight answer
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
This requires voice_states. did you enable this intent?
how you define intents now?
intents = discord.Intents.default()
all i have is that. idk how id write voice_states
discord.voice_states
the .default one does have this intent
Then i have no idea what the problem is. its weird because my bot does join the chat
you have any error handler?
i am not leet coder. I only have an if and else. but i know that it is awaiting forever since it is not allowed to join
someone told me captcha is blocking it. idk how true it is
and i dont believe it since there isnt even any audio being played
the reason you dont get the other print in the console is mostlikely that the connect method errors but you have error handler silencing it
other errors get shown. im not sure why not this one
did you try debugging it?
there is one line needing a debug in that example code but yes
what do you understand as debug
print line
and what did you try
i know there is some magic you can do in debug mode but i dont know how to use it.
i showed you.
@client.command()
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
print("Attempting to join voice channel...")
await channel.connect()
print("Joined voice channel successfully!")
else:
await ctx.send("broken")```
```lsd2#0 .join 1133330391730765854
Attempting to join voice channel...```
by debugging i mean print out varriables what do they store
so you wish for me to print the channel
for example what channel is
lsd2#0 .join 1133330391730765854
General
Attempting to join voice channel...```
i see now that it is not an id
maybe that has something to do with it
what you print out
it printed out General and Attempting to join voice channel...
how about channel.id
Have you set up logging
lsd2#0 .join 1133330391730765854
1133323696698818593
Attempting to join voice channel...
and is it the desired channel id you want it to join?
Yes
Its there right now but it doesnt say that it ever accomplishes its task of joining
is the Rust something the bot?
Yes
Maybe because you're trying to connect to a VC you're already connected to?
i am not trying to connect. i am trying to get the bot to connect
.. so it does what it supposed to
its supposed to pass
await channel.connect()
but it never gets past it
what is supposed to pass
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
print(channel.id)
print("Attempting to join voice channel...")
await channel.connect()
print("Joined voice channel successfully!")
else:
await ctx.send("broken")```
print("Joined voice channel successfully!")
it never gets to that point. thats the huge issue i am facing

cause you are already connected
then why doesnt it get to
print("Joined voice channel successfully!")
add a case where its already connected to the voice
I am invisible it seems
It joins when i run the command, '.join' therefore, it is not already connected to the voice when it is awaiting voice connection
well 
it may look like its there, but the bot has no capability of utilizing the audio channels
thats why it makes no sense.
should be some errors but doesnt throw any
or you silence them
are you able to show some code?
Sure
intents = discord.Intents.default()
client = commands.Bot(command_prefix=".", intents=intents, help_command=None)
@client.event
async def on_message(message):
print(message.author, message.content, message.channel.id)
await client.process_commands(message)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.command()
@has_permissions(administrator=True)
async def clean(ctx, llimit: int):
await ctx.channel.purge(limit=llimit)
await ctx.send('Cleared by <@{.author.id}>'.format(ctx))
@clean.error
async def clear_error(ctx, error):
if isinstance(error, commands.errors.MissingPermissions):
await ctx.send("You cant do that!")
@client.command()
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
print(channel.id)
print("Attempting to join voice channel...")
await channel.connect()
print("Joined voice channel successfully!")
else:
await ctx.send("broken")
client.run(TOKEN)```
thats most of it. the rest is just other classes
do this
@little tendon
did this and
client.run(TOKEN, log_handler=handler)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py", line 390, in <module>
client.run(TOKEN, log_handler=handler)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 663, in start
raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys()))
TypeError: unexpected keyword argument(s) ['log_handler']```
what version of discord.py is that
!d discord.Client.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
newest i think. updated today
Or, it's not discord.py
yeah is that discord.py? @little tendon
import discord?
import discord doesnt mean its discord.py
how about you do pip show discord.py in console
Name: discord.py
Version: 1.7.3
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: MIT
Location: c:\users\starf\appdata\local\programs\python\python38-32\lib\site-packages
Requires: aiohttp
Required-by:
C:\Users\starf>```
version 1.7.3
:0
xd. newest discord then xddd
lol lets see what happens now.....
File "C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py", line 390, in <module>
client.run(TOKEN, log_handler=handler)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 663, in start
raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys()))
TypeError: unexpected keyword argument(s) ['log_handler']
Process finished with exit code 1
``` this still happens.
They probably have multiple Discord libraries
inb4 pycharm venv confusion
dont blame my pycharm
theere was a code that removes all i saw @turbid condor post it xd
Yes my brain exploding
Zzz
Lemme get it
π
i did
linked it already
i ran
and how about you try to run code now?
Traceback (most recent call last):
File "C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py", line 390, in <module>
client.run(TOKEN, log_handler=handler)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\starf\PycharmProjects\AudioAnalyser\venv\lib\site-packages\discord\client.py", line 663, in start
raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys()))
TypeError: unexpected keyword argument(s) ['log_handler']
Process finished with exit code 1
π’
you ran pip install -U discord.py?
earlier yes, when u sent it
import os
import sys
py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives"
os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
Are you doing this in the pycharm terminal
at the top of your script print this print(discord.__version__)
This one?
yes
yes but already linked it slow guy
.
well the code im running in a new file
Oh i didn't see

in same evnv
what does it print @little tendon ?
When you ran pip show discord.py it didn't show a venv location so
Location: c:\users\starf\appdata\local\programs\python\python38-32\lib\site-packages
shows this
Can you check the pycharm packages tab
can you show the discord.py version
search for discord.py
uninstall discord
Does pycharm terminal not automatically activate the venv
Yall telling me magical spells.
it does
i uninstalled discord
and does it work now?
lmfao i sent .join and now it shows this.
C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py:387: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
client.add_cog(help_cog(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\starf\PycharmProjects\AudioAnalyser\RustSolutions.py:388: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
client.add_cog(music_cog(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
We have logged in as Rust Solutions#8637
lsd2 1133330391730765854```
progress
At least now it's actually discord.py
.add_cog must be awaited π΅βπ«
i can always add the cogs into the main class later
We have logged in as Rust Solutions#8637
lsd2 1133330391730765854
lsd2 1133330391730765854
lsd2 1133330391730765854
brain is gonna explode
ctx isnt getting passed?
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
β’ The message was sent by the client
β’ The message was sent in direct messages
β’ The message mentions the client
This applies to the following events...
The bot needs this intent to process commands
intents = discord.Intents.default()
intents.message_content = True```
We have logged in as Rust Solutions#8637
lsd2 .join 1133330391730765854
1133323696698818593
Attempting to join voice channel...
Joined voice channel successfully!
YOOOO
Xd... well thats awesome. but there is ONE more thing i cannot get working.
it is this monster.
@client.command(pass_context=True, name="playtest", help="Plays a local audio file")
async def playtest(ctx, filename: str):
print(f"Attempting to play file: {filename}")
try:
voice_channel = ctx.message.author.voice.channel
print(f"Found user's voice channel: {voice_channel}")
except AttributeError:
print("User not in a voice channel.")
return await ctx.send(
"No channel to join. Make sure you are in a voice channel.")
permissions = voice_channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
print("No permission to connect or speak.")
return await ctx.send("I don't have permission to join or speak in that voice channel.")
voice_client = ctx.guild.voice_client
if not voice_client:
print("Bot not connected to a voice channel, attempting to connect.")
await voice_channel.connect()
voice_client = discord.utils.get(client.voice_clients, guild=ctx.guild)
print(f"Connected to voice channel: {voice_channel}")
else:
print("Bot already connected to a voice channel.")
await asyncio.sleep(1)
try:
print("Trying to play audio.")
voice_client.play(
discord.FFmpegPCMAudio(source=filename, **FFMPEG_OPTIONS, executable="ffmpeg")) # playing the audio
print("Audio playing.")
except Exception as e:
print(f"Failed to play audio. Error: {e}")
await ctx.send(f'**Now playing:** {filename}')
print(f"Sent now playing message: {filename}")```
Attempting to play file: playtest.webm
Found user's voice channel: General
Bot not connected to a voice channel, attempting to connect.
Connected to voice channel: General
Trying to play audio.
Audio playing.
Option reconnect not found.
Rust Solutions#8637 **Now playing:** playtest.webm 1133330391730765854
Sent now playing message: playtest.webm
but i never would have figured out the discord.py thing since i thought they were the same thing.
OH MY GOOOOOODSSS
I GOT IT BOYS AND GIRLS AND EVERYONE
π
voice_client = ctx.guild.voice_client
if not voice_client:
print("Bot not connected to a voice channel, attempting to connect.")
vc = await voice_channel.connect()
voice_client = discord.utils.get(client.voice_clients, guild=ctx.guild)
print(f"Connected to voice channel: {voice_channel}")```
π
Hey guys I made a discord bot on pycharm but whenever I close pycharm the bot goes offline. How do I make it so the bot is up at all times even if my pycharm is closed?
Host it?
self host it by running it through your terminal
Where can I find a discord bot coder ?? Because I need to hire one!
Just don't buy anything under 50 bucks lol
@client.event
async def on_message(message):
if message.author.bot:
print("Nevermind guys!")
return
bucket = cd_mapping.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
channel = message.channel
permissions_to_remove = discord.PermissionOverwrite(send_messages=False)
permissions_to_restore = channel.overwrites_for(message.author)
await channel.set_permissions(message.author, overwrite=permissions_to_remove)
await message.channel.send(
f"{message.author.mention}, that is way too fast. You are disabled from speaking here for 1 minute."
)
await asyncio.sleep(60) # Use asyncio.sleep instead of time.sleep in async functions
await channel.set_permissions(message.author, overwrite=permissions_to_restore)
else:
await client.process_commands(message)
This is my code for a cooldown. When I run it and go over 20 messages per miutes, Irt does ssay "That isway too fast" But it doesnt disable users permissions. Whats going on help.
Hello. I have a bot that has its commands synced fine upon logging in to Discord. Everything works fine and commands respond properly. Upon joining a new server though, all commands are stuck in a "thinking" state and bot never replies. If I reconnect the bot, they seem to sync fine to that new server and work again
a dumb question
can i code a bot on the idle shell?
are you syncing commands when logging in?
yes
can you show your code
@client.event
async def on_ready():
await client.tree.sync()
@client.event
async def on_guild_join(guild):
await client.tree.sync(guild=guild)
also you shouldn't sync when logging in. It's unnecessary - you only need to sync when your commands change
you also dont need to sync every time the bot joins a guild
the commands are globally synced with discord
Make a sync command that only you can call and use it whenever you want to update your commands
can someone tell me the importance of Async and await?
and how to use them
and for what?
ty
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
check out the guides
removing this code didn't change the behavior on newly joined servers. Commands still don't work there
did you make a sync command ?
async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object],
spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")``` @grim robin
still nothing. If I disc/reconnect the bot they all work fine
did you run the command?
yes
I removed the previous sync lines in my code and added your command
run it in a newly joined server
can I see how you ran it
you should only have to do (your prefix)sync in your main guild. It will sync globablly to all servers
you dont need to run it again unless you change a command or add new ones
@upbeat ice
@grim robin
@client.event
async def on_message(message):
if message.author.bot:
print("Nevermind guys!")
return
bucket = cd_mapping.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
channel = message.channel
permissions_to_remove = discord.PermissionOverwrite(send_messages=False)
permissions_to_restore = channel.overwrites_for(message.author)
await channel.set_permissions(message.author, overwrite=permissions_to_remove)
await message.channel.send(
f"{message.author.mention}, that is way too fast. You are disabled from speaking here for 1 minute."
)
await asyncio.sleep(60) # Use asyncio.sleep instead of time.sleep in async functions
await channel.set_permissions(message.author, overwrite=permissions_to_restore)
else:
await client.process_commands(message)
This is my code for a cooldown. When I run it and go over 20 messages per miutes, Irt does ssay "That isway too fast" But it doesnt disable users permissions. Whats going on help.
does the user have elevated permissions that still give them access?
what does that mean
itn doesnt disable it for a minute like the coee ssy
code says*
what permissions does the user you are trying to disable permissions for have?
print(message.author.guild_permissions)
add this before you sleep
Hey, I have this slash command that should show a View with some buttons
class ModrouletteView(discord.ui.View):
def __init__(self):
super().__init__()
print("here")
@discord.ui.button(style=discord.ButtonStyle.primary, label="no")
async def participate(self, interaction: discord.Interaction, button: discord.ui.Button):
pass
@discord.ui.button(style=discord.ButtonStyle.red, label="yes !", emoji="π€")
async def roll(self, interaction: discord.Interaction, button: discord.ui.Button):
pass
@self.slash_command(name="hi", description="yes")
async def modroulette(interaction: discord.ApplicationContext):
await interaction.respond(embed=MyEmbed(), view=MyView())
The here is printed but for some reasons it doesn't show the view
is the self.slash_command(name="hi", description="yes") supposed to be a decorator?
yes it is I forogot to paste the "@"
is that inside a cog?
A discord.Bot
what library is that
pretty sure thats not how to register a slash command in it inside a class
everything works
also if this method is inside a class it must have self param
can you show more code?
cause with this it looks like shouldnt work maybe im not getting osmethjing
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yea true
But I don't wanna send all my code π
Basically this is shown
But not the button
class ModrouletteView(discord.ui.View): you create other view view=MyView()
cuz I added the same script but edited the names
don't worry it's litterally same but with other names
well with more context of code where its located and how its defined i cant tell anthing more
that would not help u
well if you know better than me
that's not what I mean
Just the code is basically a bot and as you saw it works except the view
but i dont really care what commands you have and what it does i just wanna see the context of this code snippet you provided where its located and how its defined
well ok
there are useless variables cuz I removed commands that contain sensitive info
as api key
thats interesting that this command works ```py
@self.slash_command(name="modroulette", description="Get someone kicked out of the server >:D")
async def modroulette(interaction: discord.ApplicationContext):
await interaction.respond(embed=ModrouletteEmbed(interaction), view=ModrouletteView())
why cant you define it outside class? when creating bot instance
cuz it's part of classes.py file
And my main.py should not contain any discord stuff
class ModrouletteView(discord.ui.View):
def __init__(self):
super().__init__()
print("here")
@discord.ui.button(style=discord.ButtonStyle.primary, label="Participate")
async def participate(self, interaction: discord.Interaction, button: discord.ui.Button):
pass
@discord.ui.button(style=discord.ButtonStyle.red, label="Roll !", emoji="π€")
async def roll(self, interaction: discord.Interaction, button: discord.ui.Button):
pass
Can you see what's wrong?
no..
oh yeah the components are declared inside __init__
that's basically why I ask
The buttons are being defined in the class' __init__
OH
Just move them down an indent
π
@upbeat ice
I ran it
and it printed:
<Permissions value=140737488355327>
@Bransdon
@upbeat ice
Are you the one testing this on your account?
yes
What permissions do you have in the guild
do I check this on the developer portal.
You can check in the server settings. Is it your server?
Then that's why you can still access the channel
ok
Your perms > send messages
i have several alt account tjough
Try on an alt account with basically only the permission to send messages
ok
Doesn't Discord have the show as role thingy
Yeah it does
@upbeat ice this is @gilded depot 's alt account
Ok
just testing now
@upbeat ice you are actually a lifesaveer
it workedon this alt ccount
thx so much
π
@upbeat ice I have another query
What is the best way to convert commands with traditonal prefixes into slash commands. right now all my commands are using client.command
sure go ahead
transition them to app_commands.command
if you are using discord.py you can use hybrid_command it will make them prefixed and slash command at the same and does not require much changes
Whats the difference between hybrid and the one brandon said
that like i said hybrid registers two commands one is with prefix and one is slahs
while when you register app_command its only slash
Hello, ive been searching all day trying to find a way to make a list to show every role like dyno, but i couldnt find anything so whats a way to do it?
you need to typehint the argument as discord.Role
π
@upbeat ice go to #1035199133436354600
@upbeat ice the one about the warn command
i need help, ive tried several times to add buttons, onto embeds, but it never works for me, when i run the command, it gives errors, not the editor, someone please help me further upon this (im wanting the buttons for a bot invite link)
Show the errors maybe
Hey im trying to get into coding my own discord bot, any tips as to how i should get familiar with the discord library?
There are a lot of examples in the discord.py github
Reading these would be helpful
so basically i have a discord bot
and i make it online everyday thru my terminal
and in this terminal i added options like for example info and exit
and whenever you type those it works perfectly
but the only problem is the bot is just online and doesnt respond to the commands anymore
if someone could help me further more i will send the code in dms
please help :D
@frigid estuary
Hm.... did you give it the intents
Check intents
can anyone share the link of drag down funtion in discord.py docs
You mean select option?
yess
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
thank u very much
how to stop this log spam
Show your tasks and how are you running them
well, it seems it will be hard to answer
https://github.com/Rapptz/discord.py/discussions/9038#discussioncomment-4031478
Easiest way would be to disable warnings
π€
xd
how do u do that
thanks , the task is set the condition , time = time
Why is timezone +5:53 π§
isnt that the seconds?
Seconds are 00
ISO8601
If you actually add that "timezone" to first time you will get close value to second one
can someone also help out with like how to attach a local file in attachments ? i am using paginator so cant use normal .send(file =f ) method
https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-upload-an-image
https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-use-a-local-image-file-for-an-embed-image
I don't know about paginator (i always written it by my own), but that's how you can send the images ^
Hey so I'm trying to get my bot to respond to specific content in people's messages, basically like a moderating tool
Internet research and chatgpt lead me to this
So it technically works and responds to a message when it contains "IP", but it also recognizes it if it's within a word, meaning it responds, for example, to the word "nipple"
Furthermore I get an error message in the terminal
I get these errors even though nothing is happening
define bot
oh
bro
you defined your bot as client
so why are you using bot?
i am not that good so i used paginator directly π
idk it kept showing errors with "bot" so I just switched it to "client" π
how would I go about defining "bot"
...
hey man if I had this shit figured out I wouldn't be on here π
client.process_commands(message)
not bot.process_commands(message)
you need await it
He is using an actual client it looks
what does that even mean
....
Client and Bot are different classes. Client has no built-in prefix commands.
its my first time trying this type of stuff π
yea but if I use "bot" it just does another error message
You need to define it ofc
yea so how would I define it
ok change @client.event to @client.listen()
then remove the process commands
yes
kk i'll restart the bot and tell u
so I'm guessing I need to define client
or whatever
yeah your right
show the top of your code
scroll down a bit
show me line 9 to line 16
I want to link the commands file located in the 'commands' folder within my 'discord' folder to my bot file. How can I do that?
intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='>', intents=intents)
do I just slap this in it
client=commands.Bot(command_prefix='your-prefix', intents=Intents.all())
delete the intents varible
Or do everything by your own
!d discord.ext.commands.Bot.add_command
add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")
Changed in version 2.0: `command` parameter is now positional-only.
under the import logging put from discord.ext import commands
client.add_cog(name(client))
Is it like this?
?
under from discord.ext import commands put from discord import Intents
do i add that
no
which one is better discord or nextcord
bro read the error
o
it even says what you need to do
it does
zagzag
.
"Did you mean: 'Intents"
uh In my opinion discord
delete that code the client = discord.Client(intents=Intents)
delete this part ?
yes
replace app_commands.CommandTree(client) with client.tree








