#discord-bots
1 messages Β· Page 193 of 1
its not a disc. ban
huh?
its for a game
this is quite a discord-bots server
yeah so throw it into a database to log it
to log those bans, and i thought a data base for info would be best
hence the question
i used sqlite3
There's Dbviewer - a gui database application that you can use for creating your tables and then any troubleshooting
does it work for postgres? π π
no idea
sad
they might have their own tool
their own postges?
yes
tyvm, time to read π
eh.. pgadmin kinda sucks
but i guess there is no choice
@client.command()
@commands.has_permissions(manage_guild=True)
async def toggleinv(ctx):
guild = ctx.guild
if guild.features.invites_disabled:
await guild.edit(features=discord.GuildFeatures(invites=True))
await ctx.send("Invites are now enabled in this server.")
else:
await guild.edit(features=discord.GuildFeatures(invites=False))
await ctx.send("Invites are now disabled in this server.")
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'invites_disabled'
Anyone know what the right attribute is to reference if invites are disabled or not? Thought it was invites_disabled according to https://discordpy.readthedocs.io/en/stable/api.html?highlight=pause invites#discord.Guild.edit but I guess not..
bump on this one please
How can I use queue and prevent users from joining the voice channel and from taking up someone else's spot?
what do i need to write on on_message at the bottom so every command is working again
try guild.features["INVITES_DISABLED"]
cause guild.features is a list
I am so unbelievably lost with this database stuff, i just don't know how to start
I have a datetime like this 2022-12-28T15:15:02.947Z
and I would like to use this
DatetimeF = discord.utils.format_dt(dt, style="F")
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
format_dt takes a datetime.datetime object, it that a repr of it?
repr?
Also ive been trying to format it to datetime object but i keep getting error
ValueError: time data '2022-12-28T15:15:02.947Z' does not match format '%Y-%m-%dT%H:%M:%S:%fZ'
Api
every object has a repr that shows up when you string it
which API?
roblox api
!e ```py
import datetime
print(datetime.datetime.fromisoformat( '2022-12-28T15:15:02.947Z'))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2022-12-28 15:15:02.947000+00:00
use fromisoformat
i just managed to get it working but is this prefered over strptime
a lot
Okay
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
when I did just datetime i got
ValueError: Invalid isoformat string: '2022-12-28T15:15:02.947Z'
did you do py import datetime or ```py
from datetime import datetime
!e ```py
from datetime import datetime
print(datetime.fromisoformat('2022-12-28T15:15:02.947Z'))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2022-12-28 15:15:02.947000+00:00
is it because im using a variable?
!e
from datetime import datetime
dt = "2022-12-28T15:15:02.947Z"
print(datetime.fromisoformat(dt))
@winged linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
2022-12-28 15:15:02.947000+00:00
I wonder why mine doesn't work
can someone review this code for blackjack: https://paste.pythondiscord.com/adabidetum
i'm not sure if it's good to have a view depend on the code that calls it...
(if anyone wants the view code i can share as well)
This is the first time I've tried using discord.py in a while, and I'm trying to set up a bot to use, but every time I try to run it, it returns this:
- File "main.py", line 22, in <module>
- bot.run(os.getenv("TOKEN"))
- File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
- return future.result()
- File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
- await self.start(*args, **kwargs)
- File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
- await self.login(*args, bot=bot)
- File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
- await self.http.static_login(token.strip(), bot=bot)
-AttributeError: 'NoneType' object has no attribute 'strip'
This is where I initiated it:
bot = discord.Client(intents=intent)
load_dotenv()
bot.run(os.getenv("TOKEN"))
no, Context is only for hybrid commands and message commands
you use Interaction for slash commands
your environment variable is not loaded
or you dont have it set at all
thats what someone else said, but I do
message cmds use interaction too 
why did you use diff highlighting
just cause its an err
your environment variable is not loaded
idk its just smth i do
do you use python-dotenv?
and did you call the load_dotenv function? just importing it wont do anything
you can do that without a bot by using announcement channels
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Ignoring exception in command paid_id_mines:
Traceback (most recent call last):
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 356, in paid_id_mines
await ctx.send(embed=em)
UnboundLocalError: local variable 'em' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'em' referenced before assignment
Ignoring exception in command paid_id_mines:
Traceback (most recent call last):
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 364, in paid_id_mines
await ctx.send(embed=em2)
UnboundLocalError: local variable 'em2' referenced before assignment
so confusing π
anyone can help me , my code is working but it doesnt show the message i send on my server to another server.. it only shows the authors name like this on the picture
import discord
TOKEN = 'xxxxxx'
SOURCE_CHANNEL_ID = xxxxx
TARGET_CHANNEL_ID = [xxxxxx, xxxxx]
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
@client.event
async def on_message(message):
if message.channel.id != SOURCE_CHANNEL_ID or message.author == client.user:
return
for target_channel_id in TARGET_CHANNEL_ID:
target_channel = client.get_channel(target_channel_id)
await target_channel.send(f'{message.author}: {message.content}')
client.run(TOKEN)
@shrewd fjord
fixed now i changed the intents.default to intents.all
how to set an add_field under a set_image ?
add a if message.author.bot == False:
Hello. New to coding and Python, been using ChatGPT to help me this past month, but every time i feel like im getting somewhere, i feel like i hit a point of no return where i have to restart. I'm wanting to code my own custom Pokemon discord bot, and am curious where'd be the best place to ask for help. Would it be here or in the #1035199133436354600 and just create a thread?
i would try start something a bit easier
when you are new to py
not the kind of attitude i'm looking for, i will look elsewhere then, thanks π
why the == False?
that's not possible
he wasn't trying to be rude, if you're having trouble with something take on an easier project first
So i'm creating a Pokemon class, and i'm adding attributes and methods. My current problem is i've seen attack as both and attribute and as a method, but never both, so i'm curious if there's any specific benefit to either just have it as an attribute, or as a method
think i just answered my own question typing it out lol
attack attribute is the attack stat where the method is the actual action of attack
would be nice if it would be possible cause footer a kinda small you know what i mean
you can use a thumbnail
its a like you start a fight with someone
what do you mean?
wait
it like you punching someone with a gif
and hte field should say who has won the fight
ok
why don't you just add it above
Then just use set_image, what's bad about it
he wants to add a field below the image
and i think a footer would be to small
Footer exists
just put the field above the image
Then there's no way
or use the description
and to this so the bot dont uses on_message on it own messages
so it would literlly spam without it
ah he has it already
didnt read the client.user thing
but it still would be activated by other bots
there's no point in doing x == False when you can just do not x
is False is much more preferable than either
is False > == False > not
await client.wait_for("message",check=check) doesnt work, it just detects " "
you don't have message_content intents
or a badly configured check predicate
why?
OMG THANK YOu
not x can be true even if x is "" () [] or 0
== False can be true even if x is 0
I have been working on this for the past 20 min how could I fix it?
I'm trying to make the but log the ticket transcript into a channel
error:
TypeError: Guild.get_channel() got some positional-only arguments passed as keyword arguments: 'chan
@slate swan could you help?
and that's somehow preferable?
not always, actually, almost never
.
channel_id is a positional argument
not a keyword argument
yeah its basicly the same
they're different
why did you say it was more preferable than not?
im talking in general
why they are diffrent
is bool is mostly more preferable than not
how
it might work unexpected in many cases
!e ```py
async def foo():
return False
if not foo():
print("yes")
else:
print("No")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:4: RuntimeWarning: coroutine 'foo' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
003 | No
if foo() is False was used here it might atleast catch attention of the user
not x is safe to use where the return type is fixed to be bool yeah
I actually find myself doing the latter a lot more, regardless if I know the type beforehand. it's also, y'know... less characters
if it works , it works, lol.
Kek
what is the inline thing
Is it possible to have nested groups?
Like, a command inside a group inside a group?
class Group1(app_commands.Group):
class Group2(app_commands.Group):
@app_commands.command(name='command')
async def stuff(interaction: discord.Interaction)
'''Do Stuff'''
Like that?
If so, how would you initialize it?
Groupdef = Group1(name='group', description = 'Group for dealing with x commands.')
client.tree.add_command(Groupdef)
Like that?
Why
if the inline equals to the boolean True. will it be like one under another under another right
Did you even look at it
inline means in same line
non-inline means in different line
oh
in-line
bump
Just create subcommand, and no one declares classes like that
it's how I was taught
If you have a better solution, I'm all ears
its possible to have sub groups in slash commands ( supported officially by discord api ) but discord.py'a app command system is under documented lol
Who taught you that
The glorious being known as myself.
Which, as usual, likes to find the most obscure ways to do things lmfao
class inside a class is evil 
I remember there's a deco for subcomamnd
@slate swan
Evil, you say?
oh wait, you were there
my bad
I shall search the API
what is the function for server counts and members count
tatakae
Should I use lightbulb?
if you wanna use hikari, totally yeah
you'll have to rewrite all your discord related code tho πΆ
Can I set up multiple bots on one linux vps? Like I'd just create another service ?
So i'd just add another service?
i was considering the single IP
you can
yeah thats one issue
but you won't really get ratelimited as long as you're not doing something fishy
I need help about my code , unique roles are pinging multiple times

I tried putting previous_messages already
About what
im trying to get back in coding and everytime i run my code it says this:
Can i dm u
anyone?
dont name your bot file as discord.py
is there a way for discord.py to see recent vanity url code activity?
async def on_guild_update(self, before: vanity_url_code, after: vanity_url_code):```
this example doesn't work, says its not defined.
because the example doesnt exist anywhere
its my example, ive tried it
the typehint should be discord.Guild
didnt work as planned
ah i will try that
and then you check before.vanity_url and after.vanity_url
!d discord.Guild.vanity_url
property vanity_url```
The Discord vanity invite URL for this guild, if available.
New in version 2.0.
dattebayo

I want to make a discord bot to play music, I'm just a beginner in python, i can only do basic stuff.
Can someone help me?
I just want basic features like, play , pause, skip , from YT. & Spotify.
!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)
Ok not YT or Spotify.
I want to make a discord bot to play music from my local files to VC, I'm just a beginner in python, i can only do basic stuff.
Can someone help me?
If there are emojis in an embed which the bot canβt access will the embed be sent?
a?help (command / cog name) works but somehow nothing comes when I use a?help
programme it lol
send_bot_help iirc
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases = ['leave'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def quit(self, ctx):
dbfunc = self.bot.database_handler
userid = ctx.author.id
cid = ctx.channel.id
match = await Match(ctx)
playerlist = await Playerlist(ctx)
is_quitting = False
created = await self.bot.db.fetch('SELECT * FROM match WHERE matchid = $1', cid)
if created == []:
await ctx.send(f'**{username}**, game has not been created')
else:
if userid == match['matchhostid']:
await ctx.send(f'**{username}**, you do know `ep stop` exist for some reason?')
else:
if userid == playerlist['player1id']:
await dbfunc.setIntValue('player1id', 'playerlist', cid, 1, 'matchid')
is_quitting == True
elif userid == playerlist['player2id']:
await dbfunc.setIntValue('player2id', 'playerlist', cid, 1, 'matchid')
is_quitting == True
elif userid == playerlist['player3id']:
await dbfunc.setIntValue('player3id', 'playerlist', cid, 1, 'matchid')
is_quitting == True
elif userid == playerlist['player4id']:
await dbfunc.setIntValue('player4id', 'playerlist', cid, 1, 'matchid')
is_quitting == True
else:
await ctx.send(f'**{username}**, you are not in the game')
if is_quitting == True:
await self.bot.db.execute('''
DELETE FROM playercard
WHERE playerid = $1
''',userid)
await ctx.send(f'**{username}**, you had left the game successfully')
async def setup(bot):
await bot.add_cog(MyCog(bot))
why is this chungus not working
match['matchhostid'] = my userid
no error btw
donβt even get an error when I run a?help
What not working
Split your code to parts,add some prints and find where is the problem.
ok
but do u guys have any ideas on how to compress the code?
it looks very messy
aight
its because i forgot to define username = ctx.author.id π€£
but why is it not showing undefined error
I got some issues with this, it's so long and I'm reading so many duplicated lines.
thats why im asking if anyone has any idea on how to compress it
and also only 4 lines are repeated
HEHEHE
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases = ['leave'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def quit(self, ctx):
cid = ctx.channel.id
created = await self.bot.db.fetch('SELECT * FROM match WHERE matchid = $1', cid)
if created == []:
await ctx.send(f'**{username}**, game has not been created')
return
userid = ctx.author.id
if userid == (await Match(ctx))['matchhostid']:
await ctx.send(f'**{username}**, you do know `ep stop` exist for some reason?')
return
playerlist = await Playerlist(ctx)
plist = [playerlist[f'player{i}id'] for i in range(1, 5)]
if userid in plist:
player = plist.index(userid) + 1
await self.bot.database_handler.setIntValue(f'player{player}id', 'playerlist', cid, 1, 'matchid')
await self.bot.db.execute('DELETE FROM playercard WHERE playerid = $1', userid)
await ctx.send(f'**{username}**, you had left the game successfully')
else:
await ctx.send(f'**{username}**, you are not in the game')
async def setup(bot):
await bot.add_cog(MyCog(bot))
playerlist returning a dict is a violation.
AHEM
behind the scene
I cry
Function starting with a capital letter 
how do u make timestamp
i dont have any class object so ye
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
!d discord.utils.format_dt
yaya
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
im about to ping u
<t:12812912819:R>
But I recommend the function, way more readable.

timestamp
Dunno I smashed my hand against the keyboard.
But it's a unix timestamp yeah
supposed to be a timestamp
huh
Magic
what does the number stand for
Time in seconds since 1970
WTF
<t:0:F>
how do I use a list here?
if message.content.startswith(list):
pass
Iterate over the list
who thought using 1970 will be a good idea
if any(message.content.startswith(x) for x in list)
pass
ah ok, thanks
And don't override a built-in functions with a variable
It's not a bad idea either
the number is going to be so big
It's prob for the best.
Nah, like every digit added now is first hundreds then thousands of years.
10*xEn
It's going to be too big sometime in the future, at which point they will use 64-bits values which will last even longer
Clocks dropping the new DLC package after 64-bit @ year 292,277,026,596, december 4th
Also the sun is supposed to run out of hydrogen in like, 5-6 billion years
no worries the banks don't run out of hydrogen, the sun can just take a loan
possible to print out what kind of permission user have ?
!d discord.Member.guild_permissions
property guild_permissions```
Returns the memberβs guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
guild perms i know, need user
What
i need user permisisons not guild permissions
That is the member's permissions in the guild that member object is from
Read the embed
so i need user.has_permissions convert to guild.member.haS_permissions ?
not working in nextcord.
Source code: Lib/random.py
This module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.
What's the problem with it then
It's a built-in library, so it doesn't need to be in that file
oo
is there any good tutorials for making a disc bot?
Docs πΏ
where
Or use some walkthrough on github, as because i am saying yt isnt always up to date with the updates
@shrewd fjorddo you know how to do command cd with database and check it if command cd ends ?
If you want to go with discord.py, then google discord.py docs and u will get the web
Wdym ah?
What's your goal?
Just tell it.
Connect my command to database , log users who used command, who got hit by the command , and check cooldown for user
theres even other packages?
Yes, nextcord, hikari, pycord etc
Hm kinda tricky, maybe use dict?
which is the best one?
dict={
something: some value,
}
Well, people uses discord.py most of the time, and then disnake
It's depends on ur purposes
Hikari has low level API so it kinda gives you more control
Im trying to make fully functional command to add one day economic to it , and currency. That currency will be server money . While u chatting you earn some money and talking with people in voice.
So that's why i need to find a way to do database for future things
is setting up a virtual env really needed
It makes your projects cleaner, but it's not required
Yeah, then use some libraries
sqlite3-not asyncronous
aiosqlite-asyncronous
asyncpg etc etc
im trying with pymongo
But first of all u need yi learn the query anyway
pymongo is blocking
Yeah depends on you
@naive briarcoulndt find tutorial with sql3
@shrewd fjord
sqlbolt π
Setting it up, it's good fr
alr
@shrewd fjordThis database thing have any common to python ?
U may call it synchronous
Same thing
Literally so much common with python unless i am dumb, i mean the query arent common but the syntax they follow are almost same
@shrewd fjordmy brains exploded already π
am in a venv now @shrewd fjord
That's nice
Now install packages
:-:
alr
Imma gtg, catglal here anyways :)
Catgal can you give me begining of database thing ?
how would I make a custom cooldown? I basically want to exempt a user from the cooldown if they have voted for the bot in the past x hours (disnake)
@cooldowns.cooldown(1, 300, bucket=cooldowns.SlashBucket.author)```
custom cooldown
!d discord.ext.commands.cooldowns.DynamicCooldownMapping
No documentation found for the requested symbol.

Probably
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
i get this error in my venv when i try to run the disc bot code
does your Scripts folder have a python.exe?
in your venv files

totally not laughing
Ayo mods, is bullying allowed in this server (bullying a friend specially)
given what's stated in #code-of-conduct it's quite safe to say no
Sed, ifernum, you safe here >:)
make a temporary cache subclass dict or UserDict then override setitem, getitem and contains and run some check expired time function then update and make a decorator wrapper or use commands.check
Mmm alright thanks!
hi, i copy a tutorial via a YT video and i have a error:
@commands.Cog.listener()
async def on_message(message):
if message.author.bot:
return
author= message.author
guild=message.guild
async with bot.db.cursor() as cursor:
await cursor.execute ("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
Traceback (most recent call last): File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ TypeError: levelup.on_message() takes 1 positional argument but 2 were given
self ?
async def on_message(self, message)```
okay! π
now i have another error
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
author= message.author
guild=message.guild
async with bot.db.cursor() as cursor:
await cursor.execute ("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\level_system\leveling.py", line 31, in on_message
async with bot.db.cursor() as cursor:
^^^^^^
AttributeError: 'Bot' object has no attribute 'db'
self.bot?
Yes
async with self.bot.db.cursor() as cursor:
^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'db'```
stop copying yt tutorials
What kind of db ?
aiosqlite
?
You have to write you down in the vi so that you can use it later
- copying is shit
- dpy yt tutorials are shit
how do i have a view do some stuff when it starts up in __init__?
override init? what stuff tho?
i would just subclass the view
so like
i have an embed and some buttons that change said embed
i want the embed to have different startups depending on an argument
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
Hey @uncut flume!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I tried to move some of my commands to a cog for better organization but now all of a sudden the command throws an error when I call it.
!ban @user <time> <reason>
Cog code
https://paste.pythondiscord.com/xutupafate
Trackback:
https://paste.pythondiscord.com/xiwacupado
you need to pass a duration duration is a required argument that is missing.
also you have an error in your error handler
what does ModerationCog.on_application_command_error look like?
i just changed the trackback paste
it's actually AttributeError: 'Context' object has no attribute 'ban'
@ban.error
async def on_application_command_error(ctx, error: discord.DiscordException):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title=':no_entry_sign: Missing Argument',
color=discord.Color.red()
)
embed.add_field(name='Uh oh!',value='Member is a required argument that is missing.', inline=False)
await ctx.channel.send(embed=embed)
else:
raise error # Here we raise other errors to ensure they aren't ignored
send the command
hello i try to make a discord bot with python i start it but anythings work but the bot is online. what i need to do?
!ban @user 1d <reason>
the function
seems like you're missing self as the first argument, so nextcord is passing the Context object to the member parameter instead
hi, where can i deploy my bot after coding? to make it run all the time
oh my god thats actually so stupid lmfao, i can't believe i forgot to pass self
thank you
so?
uhm, what's your question?
what's the problem?
i alr find the problem
i just update the pip of discord.py
`copy_ID_01 = "xxxxxxxxxxxxxxxxxx1"
copy_ID_02 = "xxxxxxxxxxxxxxxxxx2"
first = "#role <@"
second ="> police , rank1"
import requests
#Webhook of my channel.
mUrl = "httpxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
data = {"content": (first)+(copy_ID_01)+(second)}
data = {"content": (first)+(copy_ID_02)+(second)}
response = requests.post(mUrl, json=data)
print(response.status_code)
print(response.content)`
when I run
my webhook send only the second message I don't understand why is only sending the second message
so I have Copy_ID_1 and copy_ID_02, it only send the command for copy_ID_02
this relates to the view & message itself though
How do I fix this>
?*
@bot.event
async def on_ready():
print(f"we are logged in as {bot.user}")
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
await bot.load_extension(f"cogs.{fn[:-3]}")```
Your last line of code doesn't work
how?
when I remove the await it says I need to await it which is weird
and I added @bot.event because I needed a async function to put the await command in there
@rough wave
Is your setup function async?
How do I get a forum post title and message with discord.py?
a forum post is basically just a thread
so you'd get the thread object
and use .name
Is there a way to get the thread/forum post when created?
oo. is this an event listener where I can just do async def on_thread_join?
it is an event yes
Thanks man you're the best
no problem
It needs to be async. And add_cog needs to be awaited
why are your classes lowercase
Is it possible for bot to send dm's to user's who has no dm's setting
π
discord.py 2.1.0, python 3.11.1.
if I have a interaction command (in a GroupCog):
@discord.app_commands.command(name="test")
async def test(self, interaction, param1, param2, param3):
params = [param1, param2, param3]
await interaction.response.send_message("Hello!", view=TestButtonView())
and I want to attach a button to it (this is currently outside the GroupCog):
class TestButtonView(discord.ui.View):
@discord.ui.button(label="Testing Button")
async def test_button(self, interaction, button):
await interaction.response.send_message("How are you?")
is there any way to get the params list from the test command to use in the test_button's processing or response? for example, if I want to send the params list when the button is clicked, could I get the list to use in the response?
Sure. Create an __init__ for TestButtonView, that accepts a list of the params
a lot more simple than i thought it would be, thanks!
so, now I did (the equivalent of):
class TestButtonView(discord.ui.View):
def __init__(self, params):
self.params = params
@discord.ui.button(label="Testing Button")
async def test_button(self, interaction, button):
await interaction.response.send_message("How are you?" + params)
@discord.app_commands.command(name="test")
async def test(self, interaction, param1, param2, param3):
params = [param1, param2, param3]
await interaction.response.send_message("Hello!", view=TestButtonView(params))
and I get this:
discord.app_commands.errors.CommandInvokeError: Command 'start' raised an exception: AttributeError: 'TestButtonView' object has no attribute '_children'
Attribute error
yes
You have to init the superclass too
ah
That's not how you access instance attributes either (looking at the button callback). You have to use the instance argument to access the attributes
super().__init__(...) to initialize the superclass
And you use self.params rather than just params from within your test_button function
i did do the self.params in my actual code, i made a typo in the example
the super().__init__() helped, though - thanks
I think I am ready now after 5k days learning non-stop
Those are a lot of years
π€·
(β―Β°β‘Β°)β―οΈ΅ β»ββ»
Hey @uncut flume!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Can someone help me figure out why my help command is so buggy?
I try to scroll through the pages but it only works once and then all the reactions stop working
i think this will fix it
Consider subclassing HelpCommand instead. https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96 & https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand
It only works once because you're not telling it to continue listening once a reaction has been added
how do i make a background task that doesnt loop which I can start/stop whenever
You're probably trying to access the attribute before you define it
Check out asyncio.Task perhaps?
nah did it under my bot definiton
What could be the reason behind my main help command a?help not sending anything but if I use a?help (command / cog name) it works
Iβve subclassed the help command btw
Donβt get any error when I run a?help
showing code may help
could be a suppressed error
Have you checked the debug log? Maybe you can find something there
im getting back into coding and im so confused on whats the problem here
Regenerate token, you just leaked it
you have your token in there
did you do @client.event() instead of @client.event?
also you missed the actual error part
i just have client.event
appreciate u
if i do @client.event() it gives me this error
just do @client.event
Yeah that's why you are supposed to do @client.event
@client.event and @client.event() are two different things
Actually best to use @client.listen()
it gives me this error
!code could you please send errors in codeblock in the future, images might be difficult to read
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.
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Traceback (most recent call last):
File "c:\Users\kiril\OneDrive\Desktop\Discord bot\main.py", line 15, in <module>
client.run("tokens in here")
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
Thanks, actually your question already was answered to
oh mb i didnt notice that ty
that's wrong, it's three backticks
In Python, is there a way to count all the commands that can be executed? And that by console send me the results
yes
bot.walk_commands()
is one way you could do it
ok
@bot.command()
async def cmd(ctx):
nop = bot.walk_commands()
await ctx.send(nop)
print(nop)
so can it be?
i mean bot.walk_commands() yields a bunch of commands so
you'd probably want to get their names
not even sure that code will work anyways
need help with argument
in slash commands
I want the user to type in an argument that is either mandatory or optional. for example /choosenumber 1st Number: 69 2nd Number: 420
Not sure how exactly it is done in dpy but if it's smart enough it should be like this
async def choosenumber(inter: discord.Interaction, num1: int = 0, num2: int = 0)```
will it let the user to add a number?
how do I either make it mandatory or optional as well?
By setting default value
Again I am unsure if that's proper way cause I don't use dpy, that seems logical but you should check or ask someone with experience
by "mandatory or optional" do you mean just "optional"??
like the user can fill it out or not
I mean, I want to make it required in some commands and optional in others
yk what I mean
add a default argument
is there a different function for mandatory and optional?
The code Exenifix gave me is optional argument
The bot can't choose without any number (int)
not adding a default argument makes it mandatory
what do u want to actually be elaborate
It's basic Python 
did u even understood what I meant lol
no i meant ur usecase
how do i even save playerlist in a list in database
I want the argument to be mandatory and I didn't get it what you meant by not adding a default argument
(β―Β°β‘Β°)β―οΈ΅ β»ββ»
also u said "mandatory and optional" how does that even work
async def foo(inter, a: int) this makes a mandatory
which db sql?
some argument are needed to execute the command which is mandatory, and some are not which makes it optional
def foo(bar: str):
# ^^^ required arg
def foo(bar: str = None):
# ^^^ optional arg
postgresql TEXT[]
bruh it makes it optional
What???
lmao
Both of them are required
Because you make it?
I want it mandatory wdym
I can also clearly see the default values
Then remove the default values
What's hard about that
= 0 remove that
Code for the whole class?
well, just send_bot_help, since thats what is triggered
oke
import discord
from discord.ext import commands
from discord import app_commands, SelectOption
from discord.app_commands import Choice
from discord.ui import View
bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"Started {bot.user}")
@bot.command()
async def fight(interaction: discord.Interaction):
class SelectView(View):
@discord.ui.select(placeholder='Select Weapon', options=[
SelectOption(label='Gun', value='gun'),
SelectOption(label='Knife', value='knife'),
SelectOption(label='Pill', value='pill')
])
async def select_callback(self, interaction, select):
if select.values[0] == 'gun':
await interaction.response.send_message('Gun')
if select.values[0] == 'knife':
await interaction.response.send_message('Knife')
if select.values[0] == 'pill':
await interaction.response.send_message('Pill')
view = SelectView()
await interaction.response.send_message(view=view)
bot.run('token') ```
Traceback (most recent call last):
File "C:\Users\Xmich\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Xmich\OneDrive\Desktop\New folder\Website\main.py", line 31, in fight
await interaction.response.send_message(view=view)
AttributeError: 'Context' object has no attribute 'response'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Xmich\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Xmich\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Xmich\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'response'```
no I don't
that's not bullying
It's obvious, isn't it
y not understanding my joke
message commands don't have interactions
How can you have interactions in prefix command
And why define a class inside a function
Smh these tutorials are really going wild if that's from tutorial
Don't they have always been like this
lol
sometimes there are good reasons
They always have been cringe, but mostly because they did commands in on_message or used some constructions that "work" but break all possible code styles and principles, but class in a function is something outstanding
Not in this case

singleton class
thats a possible use case
use an app_command, which you have already imported
how's that related to singleton lol
It is
data type = test[]?
you're doing a text command, your first argument will be Context instead of interaction, just change it to ctx
and then you would do await ctx.send(...)
@shrewd apex ;-;
I see alright thanks
Just text
but how do i make it a list
text ARRAY
Array might be a constraint probably if it doesn't work directly
constraint = array?
i guess
with python drivers you usually do it like ```py
"create table hello ( var INTEGER ARRAY);"
totally a bozo
ikr
Weird
Why not use uppercase πΏ
on phone, too lazy
Bro
I code in phone, and made a whole db structure with uppercase in phone
Dont be lazy ass 
we both know that code sucks
π«
How could I make one that's always there and it waits for anyone to click on it and select. Meaning it will never become and invalid interaction until the bot is turned off and it can be used by anyone and infinite amount of times.
pass timeout=None on super().init()
pree much, the default timeout is 180 seconds, so could just do view = SelectView(timeout=None) as well
Both works kek
thank you both
@tree.command(name = 'guessinggame', description = 'Starts a guessing number game.')
async def guess(interaction, number: int):
emb = discord.Embed(title = 'Guess the number!', description = f'{interaction.user} has started a number guessing game!')
await interaction.response.send_message(embed=emb)
response = await client.wait_for('message')
guess = int(response.content)
if guess > number:
await interaction.response.send_message('bigger')
elif guess < number:
await interaction.response.send_message('smaller')
else:
await interaction.response.send_message("You have guessed the number!")```
Having problem
Ye.
Error?
yes
Singleton is a class with single instance, not really "class that you instantiate once", it typically has instance classvar which is set to the only instance
Like whats the error
Traceback (most recent call last):
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 26, in guess
guess = int(response.content)
ValueError: invalid literal for int() with base 10: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'guessinggame' raised an exception: ValueError: invalid literal for int() with base 10: ''```
thats the error
Argument that is incoversible to int provided
the number is 40
oh I get it
What is command function signature and how you use it
You provided an empty string to there
where
This will let me answer you
wdym
atc = message.embeds[0].attachments[0]
how do i get the embed image
Command signature is its name, arguments and typehints
help me pls
!d discord.Attachment check methods
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
Use one that you need
i want the attachment inside the embed
its an event
async def on_message(message):
if message.author.id not in [825617171589759006,834500417014071356]:
return
else:
atc = message.embeds[0].attachments[0]
print(atc.url)```
Yeah and put this URL to corresponding place
!d discord.Embed.image
property image```
Returns an `EmbedProxy` denoting the image contents.
Possible attributes you can access are...
the error came from ```py
response = await client.wait_for('message')
guess = int(response.content)
i meant as to restrict access to the class and limit scope my bad π
btw come to bobux once and ping
@golden portal How can I make it where when they select a option from the menu it shows another menu which is only available to see for the person who selected it
thanks a lot it worked
atc = message.embeds[0].image
send another message w/ your new select w/ ephemeral
so in the SelectOption I'll add ephermeral=True?
No, in the callback
In send
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
how do I enable it
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
What would be the proper way of making it show another menu. I don't see a way to do it
now the error is that it is already been responded
!d discord.InteractionResponse read the docs
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
Returns the follow up webhook for follow up interactions.
theres too many options in the docs
Just use disnake π€π
noty
We don't have inter.response.send_message (as main method), we have inter.send with automatic followup handling
We have response and followup too, if you need them
Not like it's hard to subclass and make that in discord.py π€·
The design is very human
lol
I am dumb
complexed*
Yeah but disnake also has some nice shortcuts except its modals implementation is bad
Disnake is for lazy developers
And newcomers
okay, I gtg.. will come back to eat my brain by this
And they don't have setup_hook, you gotta override start, but that's not a big deal
That applies to dpy
Any ideas why on_listen isnt working for me. im trying to print the string and its empty?
if setup_progress[message.guild.id] == 1:
print(message.content)
if message.content.isnumeric() and len(message) == 8:```
Im using pycord π
there's nothing like on_listen
do you mean on_message?
if so, you're missing message_content intents
@bot.command()
async def shop(ctx):
class GunView(View):
@discord.ui.select(placeholder='Select Gun', options=[
SelectOption(label='Glock', value='gun1'),
SelectOption(label='Pistol', value='gun2')
])
async def select_callback(self, interaction, select):
if select.values[0] == 'gun1':
await interaction.response.send_message("Gun 1")
if select.values[0] == 'gun2':
await interaction.response.send_message("Gun 2")
class SelectView(View):
@discord.ui.select(placeholder='Select Weapon', options=[
SelectOption(label='Spray Paint ($15)', value='spraypaint'),
SelectOption(label='Gun ($10)', value='gun'),
SelectOption(label='Knife ($5)', value='knife'),
SelectOption(label='Pill ($5)', value='pill'),
])
async def select_callback(self, interaction, select):
if select.values[0] == 'spraypaint':
await interaction.response.send_message('Spray Paint')
if select.values[0] == 'gun':
view = GunView()
await ctx.send(view=view)
if select.values[0] == 'knife':
await interaction.response.send_message('Knife')
if select.values[0] == 'pill':
await interaction.response.send_message('Pill')
view = SelectView(timeout=None)
await ctx.send(view=view)```
No error but the interaction (first one) says interaction failed
after about 10 seconds
It works fine just for some reason is doing interaction failed
@slate swan Sorry yeah, its late π py @bot.listen("on_message") async def on_message(message): if message.author.id == bot.user.id: return # make sure the bot doesn't reply to itself, that would be silly! print(message.content) if setup_progress[message.guild.id] == 1: print(message.content) if message.content.isnumeric() and len(message) == 8: # message.content.startswith("https://www.battlemetrics.com" or "www.battlemetrics.com" or await message.respond(f"Awesome, So i have your battle metrics ID as follows: https://www.battlemetrics.com/{message}\n" f"Please double check that link is correct now, Its best to get it correct the first time!") print('works?') else: await message.reply('Seems to be an error?') print(message.content)
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
enable message_content intents
@slate swan I already have, py intents = discord.Intents(message_content=True) bot = discord.Bot(intents=intents)
did you enable intents on the bot app
No Idea I just enable all the intents
you're going to need a lot more intents than that lol
for example, you probably want to enable the messages intent
discord.Intents(messages=True, message_content=True)
@civic fractal could i just use intents = discord.Intents().all() ?
discord.Intents.all()
^
Ill give it a try, sure ive tried this already though π
Also what have you done to debug this? Have you verified that your bot is connected at all? Is it receiving message notifications?
Awesome, worked a dream
hm so there's certain messages don't have content
a message with only embeds or message for instance
so it might be an empty string in those cases
nice π
awesome, cheers guys
@bot.command()
async def shop(ctx):
class GunView(View):
@discord.ui.select(placeholder='Select Gun', options=[
SelectOption(label='Glock', value='gun1'),
SelectOption(label='Pistol', value='gun2')
])
async def select_callback(self, interaction, select):
if select.values[0] == 'gun1':
await interaction.response.send_message("Gun 1")
if select.values[0] == 'gun2':
await interaction.response.send_message("Gun 2")
class SelectView(View):
@discord.ui.select(placeholder='Select Weapon', options=[
SelectOption(label='Spray Paint ($15)', value='spraypaint'),
SelectOption(label='Gun ($10)', value='gun'),
SelectOption(label='Knife ($5)', value='knife'),
SelectOption(label='Pill ($5)', value='pill'),
])
async def select_callback(self, interaction, select):
if select.values[0] == 'spraypaint':
await interaction.response.send_message('Spray Paint')
if select.values[0] == 'gun':
view = GunView()
await ctx.send(view=view)
if select.values[0] == 'knife':
await interaction.response.send_message('Knife')
if select.values[0] == 'pill':
await interaction.response.send_message('Pill')
view = SelectView(timeout=None)
await ctx.send(view=view)```
No error but the interaction (first one) says interaction failed
after about 10 seconds
It works fine just for some reason is doing interaction failed
await ctx.send(view=view)
you should be responding to the interaction there
with send_message
and I would move the classes outside of the command callback
this is from photography server. they have image competitions where users can upload picture and then other members can vote. is there a way to hide the vote counts until the competition ends?
Hi how can i use easy-pil in py 3.11?
maybe use a voting system based on buttons
user sends entry to bot, bot sends entry to channel
the entry in the channel will have some sort of vote btn
then the vote count will be handled by the bot
use buttons record the votes in a database and display once time is over run a task loop for that
thanks for the suggestions. i assume this needs to be coded? there is no existing solution for it?
Why specifically easy pil
What advantages does it have
There is
I've done something like that
I always use normal pillow and it seems easy enough
i dont know
Then just use normal pillow lol
Everything you can do in easy pil you can do in pillow
does the code stay the same between pillow and easy-pil?
Cause that feels like a wrapper
I am looking to create a card for my level system
I haven't seen a tutorial for pillow, but there is one for esay pil
See some sample code https://github.com/DevotedExuDevelopersTeam/EventMaster/blob/master/utils/image_generation.py
what is the result?
can you share me the pics?
easy-pil is very easier...
Could you share it please?
from easy_pil import Canvas, Editor, Font
user_data = { # Most likely coming from database or calculation
"name": "Shahriyar#9770", # The user's name
"xp": 1240,
"next_level_xp": 5000,
"level": 5,
"percentage": 45,
}
background = Editor(Canvas((900, 300), color="#23272A"))
profile = Editor("assets/pfp.png").resize((150, 150)).circle_image()
# For profile to use users profile picture load it from url using the load_image/load_image_async function
# profile_image = load_image(str(ctx.author.avatar_url))
# profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=40)
poppins_small = Font.poppins(size=30)
card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]
background.polygon(card_right_shape, "#2C2F33")
background.paste(profile, (30, 30))
background.rectangle((30, 220), width=650, height=40, fill="#494b4f", radius=20)
background.bar(
(30, 220),
max_width=650,
height=40,
percentage=user_data["percentage"],
fill="#3db374",
radius=20,
)
background.text((200, 40), user_data["name"], font=poppins, color="white")
background.rectangle((200, 100), width=350, height=2, fill="#17F3F6")
background.text(
(200, 130),
f"Level : {user_data['level']} "
+ f" XP : {user_data['xp']} / {user_data['next_level_xp']}",
font=poppins_small,
color="white",
)
background.show()
easy-pil is just yet another dependency that isnt' really needed at all πΆββοΈ basic pillow code it is
I would like to reproduce this card with pillow but I don't know this module at all...
this one is easy asf if u want to use this
just read its docs
anyways, my question:
So basically there is a discord.File object which is a local image actually. And I want to get its link.
Like: when I click on the image (discord.File that i passed) inside embed, it opens up to a link.. so yea i want that link
please ping me if anyone can help me with this
you want to do something like setting a local file as embed image or sum?
that's already done. now i want link of that image
i can screenshare if it's hard to get or if i'm not able to explain it right
.send will return the Message object , you can use py message.embeds[0].image to get the image
!d discord.Embed.image
property image```
Returns an `EmbedProxy` denoting the image contents.
Possible attributes you can access are...
i already tried that lol
doesn't work as per expectations
uhh, can ya hop in vc & look into problem?
sum issue?
yeah 1 moment
WWTF I CAN'T SCREENSHARE EVEN IN A SINGLE CHANNEL WTF
you can dm call
Uh yeah sure
dear good afternoon. please tell me how to add a custom emoji to the description of the select menu? the usual discord emoji is added but the custom one is not
@static holly this is from one of functions
What exactly is hard
Are those constants scaring you or smth
Look at functions, not at constants, if you would want to have same thing in easy pil you would need to use them too, unless you put numbers straight in their places which can get confusing
And yeah there is a bad way of getting a pfp because I was dumb
all I want is to achieve this image...
you sadly can't use custom emojis there, thats a discord limitation
well, thank you
error:
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 64, in _suggestion
message = await channel.send(embed=suggestEmbed)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/abc.py", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'suggestion' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').```
code:
@bot.tree.command(name="suggestion", description="Sends a suggestion to our suggestion channel!")
async def _suggestion(interaction, title:str, suggestion:str):
channel = bot.get_channel(1059976520376012811)
suggestEmbed = discord.Embed(color=0xFF5349)
suggestEmbed.set_author(name=f'New suggestion by {interaction.user}', icon_url = f'{interaction.user.avatar}')
suggestEmbed.add_field(name=f'Title: {title}', value=f'Suggestion: {suggestion}')
message = await channel.send(embed=suggestEmbed)
await message.add_reaction(':white_check_mark:')
await message.add_reaction(':x:')
channel = bot.get_channel(int(1059976520376012811))
thread = await message.create_thread(
name=f"{title} Discussion",
reason="Suggestion")
await thread.send("**Like, dislike or want to add onto someones suggestion?** Do that here! In this thread, you can discuss what you like, dislike or something smiliar you'd like to see!")
embed=discord.Embed(title="Successful!", color=0x23B425)
embed.add_field(name="This command was successful.", value="Your suggestion was successfully posted in #suggestions", inline=False)
await interaction.response.send_message(embed=embed)```
The user hasn't set an avatar probably
You can use .display_avatar instead
!d discord.User.display_avatar
property display_avatar```
Returns the userβs display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
thanks
the select menu pops up when i use !test but it doesnnt edit it depending on what i choose, here's hte code
https://paste.pythondiscord.com/ocijamibig
no errors either
You set the options' values as strings but trying to compare them to integers?
It's just hard to notice π±
How can I delete an already sent select menu within the callback?
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
oop
i changed it, same thing still happens
Changed what
the option values as strings to integers
discord.py won't allow that, even if it does, it will convert it to string
Just change the thing you're trying to compare the option to strings
how can i disable a button after its clicked?
is it possible to make a bot react to a message that has a word in the setence, for example:
if i said welcome in a sentence
welcome to (server name)
welcome!
WeLCOme
it'd react to it (case insensitive)
on_message event in dpy
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content == 'welcome':
await message.add_reaction('π')```
if "welcome" in message.content.casefold()
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if "welcome" in message.content.casefold()
await message.add_reaction('π')```?
thanks also you forgot to add a : after the brackets
is it possible to have multiple bot.events but all for different things. for example, on_member_join, on_command_error and on_message
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
I'm having trouble checking whether or not a message contains ONLY emojis
You could get a list of all emojis or a try and except
split the message at ":"
and go emoji by emoji checking it in the list
if all of them are true, it means its only emojis
or use
!d discord.Emoji
class discord.Emoji```
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of `None`...
Use regex
!d re.fullmatch
re.fullmatch(pattern, string, flags=0)```
If the whole *string* matches the regular expression *pattern*, return a corresponding [match object](https://docs.python.org/3/library/re.html#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match.
New in version 3.4.
Why do you want only emojis anyway
@bot.event
async def on_member_join(ctx, member):
guild = bot.get_guild(1058181103132868619)
channel = bot.get_channel(1058184521587105853)
embed=discord.Embed(title=':sushi: WELCOME TO THE SERVER!', description=f'Hello, {member.mention}! Welcome to {guild.name}. Be sure to read #server-information and claim your roles in #reaction-roles!', color=0xFF5349)
embed.add_field(name="It would also be greatly appreciated if you joined our group, the link is below!", value=":link: ", inline=False)
await channel.send(embed=embed)
@bot.listen()
async def on_message(message):
if message.author == message.author.bot:
return
if "welcome" in message.content.casefold():
await message.add_reaction(':wave:')
if "welc" in message.content.casefold():
await message.add_reaction(':wave:')
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(":k_exclaim: **__Error!__** Command not found! To view commands, use ``/help``.")
both the ones with bot.listen work but the welcome message doesn't
no errors
I'm making a chat filter system that fetches a specific message and resends the content into lowercase via a webhook. But apparently it breaks the emoji objects in the message content
you are comparing a discord.Member object to a boolean
just do
if message.author.bot:
no?
and then, remove the first if
oh wait nvm I misunderstood, I didn't look at the code π
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/eyewovixit
Error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 102, in mute
time=convert(time)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 83, in convert
unit = time[-1]
TypeError: 'NoneType' object is not subscriptable
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'NoneType' object is not subscriptable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'NoneType' object is not subscriptable
send the command you used
wdym
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time=None, *, reason=None):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM mute WHERE guild = ?', (ctx.guild.id,))
role_id = await cursor.fetchone()
if role_id:
muterole = ctx.guild.get_role(role_id[0])
time=convert(time)```
time is predefined as None
if you call the command without time parameter
you will always get that error
oh what
yes cuz if they wont set the time itll send a message
if time == None:
em2=nextcord.Embed(title=" Error", description=f" Please set the time!", color=nextcord.Color.red())
await ctx.send(embed=em2)
return```
you haven't coded that up
you access time before checking it it's none
Like did that first time=convert(time)
yeah
Hey, create_voice_channel working, but why not working create_textchannel
you used time before knowing its value
send stacktrace
time=convert(time)
if member == None:
em1=nextcord.Embed(title=":NoaX: Error", description=f":NoaX: Please mention a member!", color=nextcord.Color.red())
await ctx.send(embed=em1)
return
if time == None:
em2=nextcord.Embed(title=":NoaX: Error", description=f":NoaX: Please set the time!", color=nextcord.Color.red())
await ctx.send(embed=em2)
return
or a better explanation
i did look
created_voice_channels = await create_voice_channels(created_voice_channels) ---- This working
created_text_channels = await create_text_channels(created_text_channels) ---- This not
send full code
okay solved this one π
smh
TypeError: Client.run() got an unexpected keyword argument 'bot'``` any idea ?
client.run(token, bot=True)
I wanted to know if this will run every 24 hours from the start time, regardless of how long it takes to update all the users, or if it will only update the users once every 24 hours after it completes updating all users?
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
users = await collection.find().to_list(length=None)
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier_and_rank = get_tier_and_rank(summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
await collection.update_one({"summoner_id": summoner_id}, {"$set": {"summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)```
Read the error
Will it wait for another 24 hours from the start time before beginning the next iteration of the loop?
hi, i have a xp and level system, all works but I would like the xp to reset to zero when the member levels up...
For example
at the end of level 3 > xp= 480/480
I want at the beginning of level 4 the member has > 0/750
class levelup(commands.Cog):
def __init__(self, bot):
self.bot=bot
self.bot.loop.create_task(self.save())
with open("level_system/users.json", "r") as f:
self.users = json.load(f)
def level_up(self, author_id):
current_experience = self.users[author_id]["Experience"]
current_level = self.users[author_id]["Level"]
if current_experience >= math.ceil((6 * (current_level ** 4)) / 2.5):
self.users[author_id]["Level"] += 1
return True
else:
return False
async def save(self):
await self.bot.wait_until_ready()
while not self.bot.is_closed():
with open("level_system/users.json", "w") as f:
json.dump(self.users, f, indent=4)
await asyncio.sleep(5)
The loop will be scheduled to run after the loop's function ends
Just do it? π€·
And JSON isn't a database
But will it start after the 24-hour interval from the start time of the current iteration, not from the end time?
how?
Set the experience to 0?
If the loop function takes longer than 24 hours, will the next iteration start immediately after the first one ends?
I already tried right after py self.users[author_id]["Level"] += 1
but without success
What's wrong then
No
It will wait until the next 24 hours
no reset xp...
Wait, yeah, it will
its possible to make bot change server icon every day ?
Show code
Yes
yeah
!d discord.Guild.edit
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") to edit the guild.
Changed in version 1.4: The `rules_channel` and `public_updates_channel` keyword parameters were added.
Changed in version 2.0: The `discovery_splash` and `community` keyword parameters were added.
Changed in version 2.0: The newly updated guild is returned...
icon kwarg
await edit(icon="link") ?
How do I solve this?
@client.command()
@commands.is_owner()
async def stop(ctx):
await ctx.send('Shutting down')
await client.logout()
print (Fore.GREEN + f"{client.user.name} PasijungΔ." + Fore.RESET)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'logout'
Where did you get that method from
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
now close is not defined
Show the code then
@client.command()
@commands.is_owner()
async def stop(ctx):
await ctx.send('Shutting down')
await close()
print (Fore.GREEN + f"{client.user.name} PasijungΔ." + Fore.RESET)
https://paste.pythondiscord.com/yofujaqoqa
So im trying to do that they can choose a language and then itll change the embed to the language they chose, for their guild not other guild
close is a method of Client object, did you even read what I sent
but idj how to tbh i tried that
so should i do client.close() ?
yay
thank you π
@slate swani newbie, but i think so you need make guild reading
wdym
i understand now that one person can change all guilds language right ?
No
then do checks
!d discord.Client.close
tried doing that now and yeah idk how to continue
@naive briarThis guy can help you
I'm a beginner 
so await interaction.response.send_message(view=view)
what's the problem?
await guild.edit(icon='link')
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'guild' where it is not associated with a value
the idea here is that you store the preferred language to a specific guild in your database, each time your bot responds you should check what that preferred language is for the guild the command got dispatched in and translate the text to it before making the response, what problem have you encountered on the way of this?
need more context, what's the rest of your code?
i just dont really know how to do that like theyll have two options and then one they choose will be it
@naive umbraThere is no rest of code, im trying to make only change server icon once per day , so i need findout how to make it to change atleast once
there has to be more code?
where is guild defined?
right, i told you how, and i'm asking what problem you've encountered that you're struggling to implement?
like, which part exactly
at the moment about the choosing which language and then change the embed to the language
wdym with choosing which language?
@naive umbraI need to know if command line is close or not, and how to put link to read
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language != "hebrew" or "english":
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
role = await cursor.fetchone()
if role:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', ( ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', ( ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
await db.commit()```
snt like that
your code lacks context, i cant help you if you don't provide me more information instead of being vague, the error is complaining about the guild variable, make sure it's defined and is accessible in the scope you're trying to use it in
right, but what exactly is the problem?

