Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "e:\python\new\bot.py", line 511, in nserverinfo
robot = len(ctx.guild.get_role(903132835915903026).members)
AttributeError: 'NoneType' object has no attribute 'members'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'```
#discord-bots
1 messages · Page 745 of 1
@quanganh.command()
async def nserverinfo(ctx):
guild = ctx.guild
name = guild.name
rolenum = len(ctx.guild.roles) - 1
create_server = guild.created_at.strftime("%d-%m-%Y")
owner_server = guild.owner.mention
membercount = guild.member_count
robot = len(ctx.guild.get_role(903132835915903026).members)
boostnum = guild.premium_subscription_count
embed = discord.Embed(title=name, color=discord.Colour.random())
embed.add_field(name="Created at:", value=create_server, inline=True)
embed.add_field(name="Owner:", value=owner_server, inline=True)
embed.add_field(name="Member count:", value=membercount, inline=True)
embed.add_field(name="Number of Boost:", value=boostnum, inline=True)
embed.add_field(name="Roles Count:", value=rolenum, inline = True)
embed.add_field(name=" Total Bot(s):", value=robot, inline=True)
embed.set_image(url=ctx.guild.icon_url)
await ctx.channel.send(embed=embed)
i have met this problem
your id is probably wrong
oke
try recopying it and trying again
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "e:\python\new\bot.py", line 509, in nserverinfo
owner_server = guild.owner.mention
AttributeError: 'NoneType' object has no attribute 'mention'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'```
;-;
do you have member intents
yes
intents = Intents.default()
intents.members = True
this one ?
well guild.owner is returning none
hmmm
please stop ping replying every last message
what are you doing with that intents object
are you passing it to the bot's constructor
i just want to mention the owner
quanganh = commands.Bot(command_prefix = '', intents=intents)
i have no idea which other times guild.owner returns none unless the get from cache fails, i guess.
you could try guild.owner_id
ok thank you
This command works when I used only pls give without any mention.
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('pls give @final pelican'):
await message.channel.send('Money Sent {}'.format(message.author.name)) ```
Can anyone help?
so firstly, you should consider the discord.ext.commands extension which allows for built in commands.
but for your current error, you need to instead look for the base command and then derive attributes/arguments later. for example,
if message.content.startswith('pls give') and len(message.mentions) > 0:
recipient = message.mentions[0]
doing it the way you are currently, you need to make conditionals for every person because the argument is hard coded
i recommend you use commands
should have a positional argument and typehint it as a member obj
this is the best way, but you should understand the error in your logic
Is someone experienced with flask?
#web-development would be a better place for this question ig , unless you are about to ask replit's keep_alive.py
Could you help me something with that? Cuz no body is really replying to me
what do you need help with?
I need help with making a discord bot dashboard for my server
!pypi discord-ext-dashboard
A webhook and request based discord.py extension for making a bot dashboard.
this may be helpful
^
havent tried anything related with that , sorry
wow 40 minutes without a message here
Not uncommon around these times
dang
its only worth mentioning to me because i heard that this was the most active channel here 😂
staff lol
JSON formatting 
ye
how to check my discord.py version
print(discord.__version__)
or on the cmd line: python -m discord -v
is 1.7.3 rewrite?
wdym?
there's two rewrite versions
the initial rewrite was to v1 which was also the async version
now there was a second rewrite to 2.0
I need some help with my bot some help pls
so I have this code that lets the user enter their name and birthdate, which then gets registered in a seperate file, but say the user decides to quit mid-way through entering their birthdate, I decided to implement this code
oh wait
I think I see it
nvm
it isnt fixed bruh
You have break before the send
break ends the loop immediately
So that send will never be reached
Why name.content when your variable is birthdate, it should be birthdate.content.
Don't use break before sending the message. Send the message, then use break or better; return.
Also this is a bit weird. Firstly, is data already defined somewhere?
And why is it global?
And why are you closing it before opening it, and then just leaving it open
async def send(ctx, message):
return await ctx.send(message)
How can I make this for me to be able to write await send("message here") instead of await send(ctx, message=[my message here]?
Yea was about to say why you closing the pointer and right after reading from it
and no check for the message to be sent from the author
Well you'd have to pass it ctx
you can't
you'd need to make it an instance method attached to a messegable instance
okay, well then what about how do I make it so that I only write await send(ctx, "message here") if possible
You've already done that
Right now, I do await send(ctx, message="my message")
they both work
oh...i thought I tried it but it raised an error let me see
I assume you're just messing around and whatever. But just in case, don't actually use a function like this in real code, it doesn't serve a purpose. If anything it just damages the readability of your code
Lol
Most active topical channel for sure
First of all, don't use globals
I definitely use methods like this in my code
and can you send me the entire code
although often I set defaults and other kwargs
and don't use replit for hosting discord bots
so it ends up being a custom send method which adds an embed and other things :)
it was just an example.
I just wanted to use it on embeds like thsi
async def ErrorEmbed(ctx, message):
embed = disnake.Embed(color=disnake.Color.red(), description=f"{self.bot.error_emoji} {message}")
return await ctx.send(embed=embed)
repl.it
Repl.it is a simple yet powerful offline IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin (beta), QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript, Scheme, APL, Lua, Python 2.7, Ruby, Roy, Python, Nodejs, Go, C++, C, C#, F#, HTML, ...
That's the job for ya
nO
lmao why does this even exist
Are eval times like 3-4 business days or something lmao
Collecting personal information, eh?
https://www.congress.gov/bill/105th-congress/senate-bill/2326/text
Oh it's even longer
7 days
doesnt matter , if its with consent
^
Who even asks for this lmao
discord is 13+ already
this is the most dumbest idea I've seen in a few motnhs
I would firstly inform yourself before sending some links with laws and everything.
in related news mee6 is shit
bruh
(mee6 has a bday feature)
yea
Lol
mee6 also has an nft feature
Well, I'd consider the year to be too sensitive
Mee6 logs stuff too
Again, it's with consent.
it actually states anyone till the age of 16 but that doesn't change the fact that it's with consent so it doesn't matter
Okay I get it
Makes me hate it even more
Read the Discord's developer policy, privacy policy and terms of service.
Nah, depends on the country, but this is #discord-bots not #lawyers-room
Hello krypton
You sent me a US bill, I'm talking about what u sent but sure let's end it
discord is us based so most rules apply to the US, some rules are different when operating in different countries but as there's no way to determine where a member resides and what laws apply to them from a bots PoV, I wonder...
My friend got banned from discord because he was 15 and in Germany u need to be 16+ to use discord, idk if that means anything
Guess gating all the commands in their bot wasn't profitable

Why do bots gate custom commands
They're so incredibly easy to make
Main reason I do open source is.. for fun
But other people might want to make money off FOSS/OSS/free software/open source

Oh, open source software

I'd say the main reason is to help the community, although not sure about you but I find maintaining a project pretty stressful instead of fun
If you want to steal the emojis ids to use in your bot send them in #bot-commands
So they don't clog up the help channels
I'm not a project maintainer... yet
So I don't know what it's like to be a maintainer of a big project
I mostly just submit patches
The code part wasn't even that stressful, it was the contributors lmao
Did any of them use.. offensive language?
Nope, my coding style is just unique I guess and I try to make everything clean
I have to do a lot of damage control
You should talk to caeden. He's making a project and I think he's constantly having a stroke because of his team
What is it that they don't like about their team
I do, then just use uptimerobot... It continues if I close my PC
He likes them but it's just really chaotic
This is why I'm rewriting my big projects entire codebase
Like really chaotic
😔
Can you show us the github repo link
Got a new private repo where my rework is, very radically different
Nice Discord API wrapper
Contributing is fun. Maintaining, not so much. Some people tend to feel too entitled.
And that's mostly because I copied a lot of the semantics
Well, I'm more of a C/C++ dev, not sure if I can rate your Python code properly..
Second that for sure, its more fun esp when it's a challenge
yes
he kicked me because i didnt have the same skill level as people who have 2+ years of experience while i dont even have a year and then he said i was never gonna be a software dev which idrc
ouch
I picked python in 2018 I guess.
Then left it ofc
...
I am trying to make a command thats basically a typeracer.
Right now it works ??typeracer sends an image with a sentance users in the channel can type it out and first to type wins. It works till here.
Now I am trying to make it such that if a user does ??typeracer @user then it challenges the user and then does that but restricts responses only to them. I have managed to get the confirmation and everything by setting user to None but I still dont get how I can lock it to just those 2
This is the part of the code https://mystb.in/WatsonChesterDaddy.python
i only have 10months of experience smh
You still seem to know much
thank you
10 months? pft I have over 525||600||+ minutes of experience
a year🚶
and yet you know more than me 🤡
no
He sweats discord bots
no i dont
so my discord bot uses mongodb to store a lot of stuff like prefixes, user messages in guilds, etc. now im making a few events, so that the bot removes all the guild related data when it leaves. i can make the on_guild_remove() events, but i want to make an on_ready() event which scans the collection and removes data of any guilds its not a part of. how can i do that?
🚪🚶🧍♂️
Could someone help 
on_ready for that isnt the best thing, you would have to get all guild ids and compare them to all the guild ids your bot is in then accordingly remove the data. The issue with this is as your bot grows dealing with larger data slows down a bot. on_guild_remove is the best way to do this.
alright, thanks for helping
kek
For me, I have been coding bots for at least 3-4 years
dayum
I remember the migration of discord.py 0.16.x to 1.x 
he said i couldnt be a software dev(dream job) so i will prove him wrong :))
Everyone can be, if you have enough confidence in yourself :)
i do a little immature kid wont stop me :))
People said I would never be happy, get a girlfriend and have a good job. And here I am, having all of this 
So you will without a doubt achieve it ^^ Not having experience in Discord bots doesn't prove anything.
love to see it ❤️
Another person back in the days when no bot accounts existed and you had to use email and password to login with the API!
oh wait you already have it :))
Just some pixels on my profile, doesn't really matter
ik but someone that has been here for so long should have atleast something to be known of

Pretty sure at this time discord.py was actually called pydiscord as well
dang thats really old
Yeah
You can probably find old forks
client = discord.Client()
client.login("email", "password")
client.run()
Was something like that
wow
That was surely longer than 3-4 years ago
👀
Yeah that was longer, I however got into really programming a bot 3-4 years ago.
That was probably like 2016 I'm guessing
I did some small tests back when pydiscord was a thing, wasn't amazed.
Yeah, that was at the very beginning, so around 6 years ago I'd guess.
Danm 6 years went past crazy fast
Remember when I signed up for discord right at late 2015
Old forks probably still have commit dates.
Anyways, I got to work on my projects; have a great day and see you later ^^
cya
Oh on this account I created it in 2017 😔
Lost the old one sadly
What happepend?
Just abandoned
No longer have the email to the account nor the password as I've transferred to protonmail from gmail
hey whats wrong
Chances are the issue is on the line above
has anyone used heroku?
if yes how did u use env variables.. did u push the env file to your github repo?
how do I use ctx.invoke in on_message event ?
bot.get_context(message , cls=cls) ?
!d discord.ext.commands.Bot.get_context
await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
Yes, however you need to await it as it's a coroutine.
Without cls=cls
That's not needed in your case.
so If i want to invoke a command I do await self.bot.get_context(message).invoke(self.bot.get_command(commandname, args='whatever') ?
As I said, you need to await it.
i did
yea it is await bot.get
And why are you using once self.bot and once just bot?
changed
so is it correct now ?
Look good, however I would save the Context object in a variable before using .invoke().
The documentation says the Context object is not always valid, and needs to be checked before.
how do i check if it is valid ?
The returned context is not guaranteed to be a valid invocation context,
Context.validmust be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke().
It's just a matter of reading the documentation :)
ctx =await self.bot.get_context(message)
if ctx.valid:
await ctx.invoke(self.bot.get_command(commandname), args='whatever')```
Seems good to me
ok thanks
The last line doesn't look right to me
which line ?
so this should be correct?
Considering the command name and the arguments are correct, yes.
ctx =await self.bot.get_context(message)
if ctx.valid:
await ctx.invoke(self.bot.get_command("play"), args=message.content)
else:
print("ttt")```
the ctx : context is invalid it printed "ttt"
any host recommendations for discord bots?
Galaxygate just 3$/mo
Also check pins
oh the vps pin?
Yeah
I checked them all turns out the galaxygate is the best option but it is up to you what to choose
ohh well Imma check out galaxygate thx
also is standard 1gb 3$ good for beginning?
Totally
yes 1gb of ram is overkill ngl
oh
okay thx
how much memory usage?
If you need help with server setup feel free to ask me because it might be difficult to figure out
With 5 bots running it's like 500mb
can i as well?
Yeah
ic thats nice
ill keep it in mind
sure 🙂
It depends the number of guilds your bot is in and events you listen to.
ik
i just wanted to know the average of it
There's no average, depends who you ask.
Why is the ctx invalid?
4GB is the bare minimum in my opinion.
got a point there
I don't see how events matter really, the important part is the cache as that is all stored in memory
How can the bot get access to cached things without listening to them.
bot.get_
Not listening to some events leads to less cache being used, as you can't use get_ but you need to fetch the data, right?
When you identify to the gateway you receive GUILD_CREATE for x amount of guilds your bot is in, this event contains the data corresponding to the guild which can be cached including it's membrrs
You won't get cached all messages if you don't listen to the events accordingly, example for the on_raw_reaction_add.
The cache is then updated when a new event corresponding to the object is received
Thus in theory due to the gateway you won't need to fetch
Wait, I meant intents, not events.
If you disable not needed intents, you don't get any of the events.
Sure, if you disabled member intents that would significantly cut the memory usage
As both member cache and user cache depend on it
Yeah, I confused events and intents; my bad ^^
can you guys keep talking about cache im learning allot
Hello
I am using a website is replit and I want to do it like when ever someone got muted by a other bot it will shows up a log
You may implement it via on_member_update event
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
Holy cow how many guilds does your bot (or bots?) serve if I can ask? Or there are other apps
Why isn't this working?
It isn't even showing an error
How do you define client
Also this method of comparing channel type is not good
Use either == operator or isinstance
How do I give default permission to user in a specific channel?
To set permissions for the channel there's this
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
isnt message content already a str
yeah
Create a docker file for your project, build a container image for your project and then the run the container
@untold token yk, not everyone is as well versed as u, with docker containers lol
@untold token could you please look at #help-falafel
You can reference docker documentation to create your own docker container image and run it
I understand that alr
Create a new one
But I know how to do all that I only need to figure out where does the docker run the file
That channel is dormant
Answer it here or in dms if possible
hey @maiden fable , do you know if on_guild_update gets triggered when a user stops boosting the server i.e when the premium_subscription_count changes
All I need is basically where does docker start running
Sure, if you want to do it in dms, docker containers is outside the topic of this channel anyways
Yes iirc
Yeah
oh ok and how to make the bot only response to admins/mods
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
I don't think anyone has tested it rn... Lemme try finding out more... Gimme some time
you mean a role or a permission?
yes
uh no a role not permission
then this
is the bot only in one server? or is the command you're talking about only being used by one server?
only the bot in one server
if the role name is moderator you can do
@commands.has_role('Moderator')
oh ok
or can I just insert the role id?
either the name or the id.
If you are giving the name, put it in a string.
If you are giving the id, put it as int
remember to keep exact spelling/capital letters if you are giving string
@spring flax sorry but the API docs don't really help in the matter, but since the Gateway sends the premium subscription count key in the guild object json, it's safe to assume that it's also called when a user boosts/deboosts a guild (:
user.discriminat is not a user paramater
don't unban a member like that.
is discriminator .-. like for member
oh ok
also
can i change member.name and member.discriminator to member.split
wait wdym
dont unban like that
@green bluff That is a very ineffective way to do it. I assume you are watching lucas.
wdym with this xD
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
hawwo! i was wondering if i can set to a variable, a type like "a list of roles"
Use this to get the member object with the given ID, and call Guild.unban on the discord object (which is a member)
what do you mean?
alternatively you can unban a discord.User
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
roles: list[discord.Role] = whatever if you are on Python 3.9+
Or something like that
Depends on your library
you can use greedy for that as well, I believe
It doesn't do anything other than let your editor know what methods it might use so it can show them to you while coding
@list_group.sub_command()
async def add(self, inter: disnake.CommandInteraction, listname:str, roles):
print(roles)
roles_id = [int(role.replace("<@&", "").replace(">", "")) for role in roles]
async with aiosqlite.connect("databases/DataBase.db") as db:
query = await db.execute("SELECT custom_id FROM lists WHERE server_id = ? AND list_name = ?", (inter.author.guild.id, listname))
list_id = await query.fetchone()
print(roles_id)
for id in roles_id:
await db.execute('INSERT INTO lists_roles(server_id, list_id, role_id) VALUES (?, ?, ?)',(inter.author.guild.id, list_id[0], id))
await db.commit()
await inter.response.send_message(f"{listname} has been added succesfully to {listname}", ephemeral = True)
i have to set "roles" as a but cant get to work it gives me ExtensionFailed("Extension 'exts.rolelist' raised an error: TypeError: unhashable type: 'list'")
Yeah but they said they want to type hint a variable
something like this?
this is type hinting
or i dont understand
Yes
im redoing the inside of the command from normal to slash
both member and user in your code are variables D_D
o ya
async def add(self, inter: disnake.CommandInteraction, listname:str, roles: Greedy[discord.Role]):
what is listname supposed to be for?
the name of the list you wanna ad the role to u.u
for dropdowns
okay so it's just one word?
yas
okay, then try this
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
doesnt recognize "greedy"
imports
i'm not using discord.py
i know
you're using disnake
!d disnake.ext.commands.Greedy
class disnake.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
it's the same thing
you need to import it
either you can import it, which you can use arg : Greedy[whatever] or you can do arg : commands.Greedy[whatever] without specifically importing greedy from commands
@client.command()
async def wsend(ctx, member : discord.Member, money : int):
cursor.execute(
f"SELECT wallet_amt FROM account_table WHERE user_id = {ctx.author.id};"
)
db.commit()
result_w = str(cursor.fetchone())
result_w = str(result_w).strip('[](),')
result_w = int(result_w)
cursor.execute(
f"SELECT wallet_amt FROM account_table WHERE user_id = {member.id};")
db.commit()
result_b = str(cursor.fetchone())
result_b = str(result_b).strip('[](),')
result_b = int(result_b)
if money > result_w:
embed = discord.Embed(
title='Don\'t try to oversmart me.',
description='You can\'t give money you don\'t have.',
color=0xff0000)
embed.set_footer(text='I mean come on that\'s common sense.')
elif money <= result_w:
result_w = result_w - money
result_b = result_b + money
cursor.execute(
f"UPDATE account_table SET wallet_amt = {result_b}, WHERE user_id = {member.id}; "
)
db.commit()
cursor.execute(
f"UPDATE account_table SET wallet_amt = {result_w}, WHERE user_id = {ctx.author.id}; "
)
db.commit()
embed = discord.Embed(
title=f'Money sent.',
description=f'{ctx.author.mention} sent {member.mention} {money} coins.',
color=0x00ff05)
embed.add_field(name=f'Wallet of {ctx.author.mention}', value=f'{result_w}', inline=True)
embed.add_field(name=f'Wallet of {member.mention}', value=f'{result_b}', inline=True)
await ctx.send(embed=embed)
``` What is wrong with this?
What problem do you have?
Does not give money to the other guy.
And stupid replit won't tell me where the error is.
do you have an error handler?
yes
keeps getting errors
which is?
ExtensionFailed("Extension 'exts.rolelist' raised an error: TypeError: unhashable type: 'Greedy'")
code please
async def add(self, inter: disnake.CommandInteraction, listname:str, roles: Greedy[discord.Role]):
Why u tryna write the Greedy class to a text file
the full command
wait what
That error comes when an object is being written into a text file or smth but Python fails iirc
yeah, a database too
async def add(self, inter: disnake.CommandInteraction, listname:str, roles: Greedy[discord.Role]):
print(roles)
pass
yeah...that won't work. one second
that converts the roles into a list of role objects
what do you want to do with them?
i need to force the type so im able to input only roles
like i did with a single channel, and or ints/strings
but i cant with multiple at time
but that's what it is though
what do you want to do with the list of roles?
get their id's?
i can get this
but not list of roles
here i'm forcing the input only as specific thing with autocomplete
Command raised an exception: ValueError: <ClientUser id=930706891699519528 name='giveawaybot' discriminator='4748' bot=True verified=True mfa_enabled=True> is not in list
what does this mean?
@mild zephyr discord API doesn't support mutliple values for one argument afaik
what package are you using?
Unless you create custom converter
disnake
i'll go for strings x3
disnake actually let you use typehints for slash commands
it does
yes x3
!d discord.ext.commands.Greedy @vale wing
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
then what is your problem? xD
i need to get multiple one at time
if i wanna ad 20 roles to a list it would be painfull to get a one at one
where do people learn how to code bots?
youtube, docs and trying (?)
k
maybe you could find more help in disnake server
Guys my PyCharm doesn't recognize intellisense for disnake, why? i allways used it and it allways worked fine
how do I give default permission to user for accessing a private channel after creating a new channel?
Sup Bois
help me please
When making a discord dashboard does any one know how do i make the url direct me to the discord login?
Join replit they will help
!code pls share in a code block man not screenshots
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.
Its replit not this server
#replit
API doesn't. Look at these types, pretty sure the library (disnake) doesn't as well. Have you tried it by yourself? I actually asked here about that before and helper told me that it is impossible to implement list of arguments in slash command context. There's just no type for that and you can check it by yourself
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
ah. You didn't mention slash commands, so I thought you're talking about normal bot commands
After creating a private channel how do I give access to specific users?
How are you able to get the error in the console can you tell me.
it's not server, i think it's guild
I want a command that sends a message to a random channel in all the servers my bot is in.
can anyone help me with that.
The message is supposed to be a argument.
It can be inbuilt, but argument is preferred.
loop through the bot's guilds, use random.choice to get a random channel from the list of the channels of the guild, then send the message to the channel
I made a leaderboard command with sqlite3 and am struggling to make it display the leaderboards per server/guild. Atm it shows a global leaderboard. Does anyone have any knowledge on this?
Thanks.
I did the same today... messed up the whole effing bot.
damn :/
Can I send in slash command interaction an embed with an ephemeral message?
Yeah
And fields index in embeds starts from 0 right?
Not too sure
mhm
ok, this is happen again, how to fix it
code (list)
map = [b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,'\n',
b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,'\n',
b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,'\n']
Can someone help me with embeds? My bot isn't sending a embed.
My code is kinda crappy, but here it is nonetheless
@bot.command(aliases=["items", "SHOP", "ITEMS"])
async def shop(ctx, *item):
#print("debug1")
#print(item)
cont = ''
member_reg = False
item_exist = False
f1 = open("economy.json", 'r')
f2 = open("iteminfo.json", 'r')
read1 = json.load(f1)
read2 = json.load(f2)
f1.close()
f2.close()
for i in item:
cont = cont + i + ' '
a = len(cont)-1
it = cont[0:a]
for i in read1:
if i["id"] == str(ctx.author.id):
member_reg = True
if item == ():
embed = discord.Embed(title="There's no shop yet ")
await ctx.reply(embed=embed)
else:
it = it.lower()
for e in read2:
if e["short"] == it or e["name"] == it or e["dname"].lower() == it:
item_exist = True
count = i["items"].count(e["short"])
if count == 0:
embed = discord.Embed(title=f"{e['dname']} {e['emoji']}", color=ctx.author.color)
await ctx.reply(embed=embed)
else:
embed2 = discord.Embed(title=f"{e['dname']} {e['emoji']} ({count} owned)", description=f"{e['desc']}\n_(Short-{e['short']})_", color=ctx.author.color)
if e["buy_cost"] is None:
embed2.add_field(name="_Cannot be bought._", value="")
else:
embed2.add_field(name=f"Buy- {e['buy_cost']} ", value="")
if e["sellable"] is False:
embed2.add_field(name="_Cannot be sold._", value="")
else:
embed2.add_field(name=f"Sell- {e['sell_cost']} ", value="")
await ctx.reply(embed=embed2)
The last statement is the one which isn't executing btw*
the embed sending part?
any errors?
It doesn't return any
the json files may be empty..
It's not empty
If it'd be empty there would be key errors most likely
Do you think you know why the embed may not be showing up?
it would have not done those steps already py for i in read1:
if read1 is empty it wont process
I checked everything (with loads of print statements), and only the embed line isn't executing
Oh yeah
The last one, I mean
@dreamy sluice try printing embed2.to_dict()
Mkay
Also do you get any errors
Nope
it returned the contents of the embed
{'fields': [{'inline': True, 'name': '_Cannot be bought._', 'value': ''}, {'inline': True, 'name': 'Sell- 20 ', 'value': ''}], 'color': 2069990, 'type': 'rich', 'description': 'A smol, insolent bug. Can be sold for 20 \n_(Short-tbug)_', 'title': 'Smol Beetle (1 owned)'}
Ye
Do you have error handlers
Nope
Try to send something other than embed
That doesn't work?
@slate swan description is not empty
He meant my field values
Ik but it is not why it doesn't work
O-o
@dreamy sluice have you tried
lemme send an example
One second
I know what that is
I don't understand why do you send that, do you think it is not sending because of this?
Yep, it sends the message
It just doesn't send the embed
Anyways if it was because of embed it would most likely raise bad request
it raises an exception for the embed ```
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required
Yeah but he gets no exceptions
maybe they have an error handler
I don't
no on_command_error event?
@dreamy sluice anyways try to do what they suggested
Oh, I do
Ah
thats what an error handler is:p
You should raise all unknown exceptions in it or print them
add else : raise error in the end , it helps u to get untraced errors
mkay
considering error to be the variable for your exception
okeh
lemme try
OK, it returned the error you mentioned @slate swan
hey i am making a trivia anti cheat kinda thing but i am getting stuck
async def interaction_check(self, interaction):
self.click.append(interaction.author)
print(self.click.count(interaction.user))
if interaction.author in self.users or self.click.count(interaction.author) != 1:
await interaction.response.send_message("Your response has already been submitted", ephemeral=True)
if interaction.author not in self.users and interaction.component.label == self.answer and self.click.count(
interaction.author) in [0, 1]:
self.users.append(interaction.author)
return await interaction.response.send_message("Your response has been submitted", ephemeral=True)
``` i am getting `disnake.errors.InteractionResponded: This interaction has already been responded to before` but before i didnt get them
You respond twice if one of your if checks is successful.
You also need to return when sending the message in your if checks.
yes ik but i didnt get that before
That's correct, but if you go in the first if statement, you also respond.
And therefore respond twice instead of once.
The last one will always be sent, and if you enter in the first if statement, it will also send a response.
not really that is only when they click the 2nd time before that didnt happen ( i am clicking 2 differnt buttons )
Has anyone worked with this: https://github.com/SilentJungle399/discord_buttons_plugin
How do you fetch message ID of the buttons.send() method
if i have a cog folder open, and in a cog named cog_one.py, I make some functions and in the cog cog_two.py, how do I import the functions i just made in the other file?
are they both in the same folder
Guys in embeds fields index starts from 0 or 1?
0
all indexs start from 0
Functions and not commands?
It is better to put non command functions to a separated module and import them from there
If you still want to import them from extension I think it's still possible to import functions you need from one file by using import statement
Also could you show files hierarchy
Whats the official import module for discord buttons
Dpy 2.0 supports it but it is no longer maintained
use nextcord
You could use fork, I don't really think you need official library
!pypi nextcord
A Python wrapper for the Discord API forked from discord.py
ooo a6
Nextcord, pycord, disnake - any of them
!pypi disnake
!pypi pincer
Functions yeah
@spring flax show please there are some nuances regarding imports
And from what cog to which do you want them to import to
From the functions cog to the utility cog
from cogs.functions import ...```
Isn't there any way to auto import them?
I remember visual studio code doing that before, if i make a function x in a cog, in another cog i write x it gets automatically imported
If you press enter once it suggest auto-import and then look upperside you will see what I mean
It just adds an import statement
Do settings need to be enabled?
I dunno, it shows up for me tho I didn't edit any settings like that
I can but it gets tedious at some points
Any extension?
That's relative import
ik and we know what happens there
I am not sure how it'd work but in absolute one it searches packages in relation to the main file. Basically . is the current folder so if we start it from main.py it could actually refer to a root folder. I don't know that much about relative imports need to check by myself
I have python extension only lol
Not counting the AI assistant it doesn't suggest autoimport
is it possible to change sleep from seconds to days?
so I can create a temp channel and set the amount of days before its deleted
<RawReactionActionEvent message_id=1111 user_id=9876 channel_id=4444 guild_id=12345 emoji=<PartialEmoji animated=False name='▒' id=None> event_type='REACTION_ADD' member=<Member id=12345 guild=<Guild id=12345 name='test' shard_id=0 chunked=True member_count=9>>>
``` how am i supposed to get what emoji was used ▒ wtf is this? should be \⚫
try typing it out like :black_circle:
it should be like emoji=<PartialEmoji animated=False name='\⚫'
well i cant grab it i want to check if the emoji used is in a list
or a dict to be more specific
that not the way to post emojis as reactions
@vagrant brookthanks ur were correct
Hello, everyone!
I would like some advice, please, on which Python package to use to build my bots, and how to structure them.
I work for a B2B startup in the HR area; we make chatbots tailored to our clients' requirements, and these bots communicate with these companies' employees over platforms such as Slack. I've been tasked with adding Discord as a platform.
Our existing logic will handle what messages to send, to whom and when, as well as process the answers we receive. We need to be able to send and receive direct messages (1-on-1), as well as listen to messages where the bot is mentioned in multi-user contexts. Our messages may contain text, images, files for the user to download and buttons. I am currently confused about Discord because the way we usually receive info from our platforms is via webhooks we expose, but so far at least I haven't seen those in Discord.
That can be because I had started building the platform handler with the discord.py package, only to find out it has been discontinued. If there is an explicit webhook URL, it got abstracted away by discord.py. In any case, I see that it has fork successors (pycord, nextcord, enhanced-discord.py), as well as unrelated alternatives (hikari). The latter offers "command frameworks" - I am still not sure what that means - like lightbulb and tanjun. So, my question is: which package should I use? What are pros and cons of each option? If I choose hikari, do I need the command frameworks, or is using just hikari enough?
Thank you so much for your attention!
Disnake and nextcord are good Discord.py forks with all old features of discord.py
As for the hikari library , using raw hikari is like using discord.Client , so you would have to use events to make your commands and stuff work
With the use of a command handler like lightbulb you can do that with no efforts using command functions as in discord.py , I'm not sure about tanjun but I've used hikari-lightbulb and it's somehow similar to discord.py's commands.Bot framework
If we talk about a fork vs hikari
Forks are derived from discord.py so for sure it would be more comfortable for you to use them
As for hikari it provides many things like complete acess the cache , better code style etc
@botmisc.command
@lightbulb.add_cooldown(10, 2, bucket=UserBucket)
@lightbulb.command(name="ping", description="Sends bot's latency", aliases=["latency"])
@lightbulb.implements(PrefixCommand, SlashCommand)
async def ping(ctx: lightbulb.Context):
"""Bot's Latency"""
await ctx.respond(f"🏓 Pong `{round(ctx.bot.heartbeat_latency *1000 , 2)}` ms !")
``` a sample code for lightbulb library
Thank you! I have actually no familiarity with discord.py, I had basically installed it, run the example code and then as soon as I tried integrating it with our existing code I needed to check code examples on their github and found out it is no longer maintained. So, if I have no preference for a discord.py fork, would you say hikari is a better option? I like that you mention better code style
I finally got to use my mod bot
I prefer disnake as a fork, but hikari is good too! It's just your preference.
any namespace rename isn't good lol
Disnake never does that.
unless u install it as discord
Hikari is a great library to try , I have a open source hikari Library bot in case you want reference
Well Disnake does not do that.. ```bash
$pip install disnake[discord]
maybe emoji id?
or the bytes version of it
\⚫
um
I am at the very beginning, I have no code that assumes I depend on discord.py, so changing the name of the import wouldn't matter to me. But yes, I will check out disnake as well.
Thank you very much, everyone!
!charinfo ⚫
Character Info
\u26ab : MEDIUM BLACK CIRCLE - ⚫
I also have another question. For some platforms we use "proxied" bots. What that means is that, while we have many different bots in our own server, each corresponding to a different customer, they all share one bot from the point of view of the platform; we only really need one webhook and then we distribute the messages it receives to the appropriate bot on our side. Would this approach be advisable for Discord? Or should we stick to our default of one bot in our servers corresponding to one bot from the point of view of the platform? The default seems to have the advantage of being way less likely to bump into rate limits.
Well using webhooks would be a better option since this would also prevent bumping into ratelimits. All the big bots like Dyno use webhooks too, to send logging messages
is there a way to limit reactions to 1 in same message or timeout on reactions ?
Oh, and could I please take a look at that open source bot you mentioned?
U can't limit them. Manually removing them would just ratelimit u
It's very basic and I made it like 2 days ago so I hope it won't be too complex https://github.com/sarthak-py/Winky
Damn seems like hikari is getting more popular 
Nice, thank you! So, one webhook URL per bot, then? How do I tell Discord the URL we're exposing for that webhook?
if you get into discord.py or lucas's server it is preferred over forks
!d discord.Webhook.from_url
classmethod from_url(url, *, session, bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook "discord.Webhook") from a webhook URL.
And hushhh , lucas with a hikari series now
Well, discord.py server doesn't really suggest a single fork since it can become controversial at some point, so it's understandable
Well, lucas just needs a new topic to make bad videos on, sooo, understandable
Imagine ban command in hikari
Lmaooo
Wait lemme copy paste it , someone sent it recently
Not there 🥲
Hikari kinda gud
I've expired form making discord bots 
I've only used disnake since the discord.py shut down so I won't give any opinions on this
Well, I'm just getting started! I've looked at hikari's doc page and seen it is in alpha and its API is unstable, so I'm gonna use some discord.py fork. Any comparisons between the available options? If I go by github stars, pycord wins, but it seems y'all prefer disnake?
Yea, disnake is a bit more stable, with faster feature releases and better updates
I got half the usual ping in disnake from discord.py
Can't happen
discord.py ping = 100ms, disnake ping = 50ms
Ping depends on your network connection, not the library
¯_(ツ)_/¯
Even @slate swan can confirm that
well, both pycord and disnake got half of the usual ping, so idk
but i prefer disnake
because reasons
disnake > discord.py ^ pycord
Is it bad?
simply depends on current websocket connection
doesn't that simply mean the net/WiFi
Haha cool!
and the code implications for that is same , atleast for all the forks
yeah that's basically it
Thanks
Someone can explain why these intentions are needed and how to correctly request from Discord access for a verified bot
so you can see all the members
When u fill the form for verification of the bot, u need to fill in the intents u need, with a valid use case
i just set my intents to all
too lazy to specify
(intents in code)
I'm talking about verified bots lol
The fact is that the bot has already been verified, but I did not ask for permission.
oh alr
Then there's a different form to request for those intents
I requested but was refused, can you tell me how to correctly request? And what should I say?
Mind showing me the mail u received?
yea
That means u can use fetch_member without using the intent
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
But the bot cannot be added to more than 100 servers, and I suppose that because of this
and
Ticku, he offline
It's verified... It should be able to be added to more than a 100 guilds
Because of Toko that I turned off these parameters
Can I somehow enable this without asking for permissions from Discrd? Verified bot
is it a good idea to leave discord.py because it got shutdown or ?
i mean, there are better forks you can use
like hikari, disnake, pycord and more
but it's your choice lol
Which one's the best in your opinion
overwrites = {
ctx.guild.id.default_role: discord.PermissionOverwrite(read_messages=True, send_messages=False)
}
category = await ctx.guild.id.create_category("SERVER", overwrites=overwrites, reason=None)
admin_logs = await ctx.guild.id.create_text_channel("adminlogs", overwrites=overwrites, category=category, reason=None)
kill_feed = await ctx.guild.id.create_text_channel("killfeed", overwrites=overwrites, category=category, reason=None)
Hello im trying to create 2 channels, im trying to set the two channels to read only
default role doesnt seem to be working though any idea how to fix it?
No. The message above clearly says you need to apply to be able to enable them.
thanks
why ctx.guild.id?
@spring flaxTo get the default role in the guild?
why id though?
@spring flax 😮
it's discord.Guild.defaul_role.
You need a guild object.
Silly me, thanks 😄
By using guild.id, you are not working with a guild object
Monged it, spent too long infront of this computer 😄
haha lol it happens
Guys how can I get the current message time
when I send a message a date near to my name is appears, How can I get it??
Exactly as it is
(user.id,))
AttributeError: 'NoneType' object has no attribute 'id'
return await ctx.send(await User.balance(ctx.author))```
async def balance(self, user : Member = None) -> int:
"""
A method that returns a user Balance
---
user : discord.Member
"""
async with aiosqlite.connect("database/user.db") as connection:
async with connection.cursor() as cursor:
await cursor.execute("""
SELECT balance FROM USERS
WHERE user_id = ?
""",
(user.id,))
if await ( x:= cursor.fetchone()):
return x
await cursor.execute("""
INSERT INTO USERS
(user_id , 0 )
""")
return 0```
try to debug this program (for example on the first line type print(user))
It depends on calling the function maybe you made balance() without passing the member parameter
I'm not professional I'm trying to help😅
how can I get the current message time
when I send a message a date near to my name is appears, How can I get it??
Exactly as it is
its fine thanks
there are some time formatters from discord that shows the message according to the people timezone
examples??
"discord unix timestamp"
import discord
from discord.ext import commands, ipc
class MyBot(commands.Bot):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.ipc = ipc.Server(self,secret_key = "a")
async def on_ready(self):
"""Called upon the READY event"""
print("Bot is ready.")
async def on_ipc_ready(self):
"""Called upon the IPC Server being ready"""
print("Ipc server is ready.")
async def on_ipc_error(self, endpoint, error):
"""Called upon an error being raised within an IPC route"""
print(endpoint, "raised", error)
intents = discord.Intents().default()
my_bot = MyBot(command_prefix="!", intents=intents)
@my_bot.ipc.route()
async def get_guild_count(data):
return len(my_bot.guilds) # get the guild object using parsed guild_id
my_bot.ipc.start()
my_bot.run()```
from quart import Quart, render_template, request, session, redirect, url_for
from discord.ext import ipc
app = Quart(__name__)
ipc_client = ipc.Client(secret_key="a")
@app.route("/")
async def home():
guild_count = await ipc_client.request("get_guild_count")
return await render_template("index.html", content=guild_count)
if __name__ == "__main__":
app.run(debug=True)```
why aren't both running together?
my bot and Quart?
so I making a color(role giver) atm i use command, but thinking of use reactions as interaction for it, but how can i prevent abuse? like if few peoples spam on n off reaction i am pretty sure u can get API-blocked duo bot gonna give n remove role each click
@slate swan ur smart any inputs? ^
@slate swan can you help me too?
@arctic python can you help?
sorry fot the pings
no need to ping all dood 😄
ikik
@slate swan app.run() is never being runned.
here
cause its in namespace __main__
what should i change?
prob just remove if __name__ == "__main__":
That just checks if it's not being imported into another file
Ipc server is ready.
Bot is ready.
didn't happen
What's the issue?
I dont know, its not a cog either
how to make both quart and my bot run
to get my bot guild count
U need to manually press F5 on both the files and run them
Your IDE won't support it most probably, so use the CMD and type in python file.py exchanging file with the name of the python file
k
@maiden fableany idea of my Q?
What's the q
this
i used slit terminal
a way to make timeout for reactions per user or so?
will that work?
asyncio.timeout?
idk
was thinking of something builtin
So you want to block user from reacting for x duration?
There's nothing in built for that... Instead u can use bot.wait_for
yeah so they cant just spam the emoji and abuse API both themself and bot that gives them roles/removes
Temporary role that don't allow reacting?
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
its not working
what should i do?
hm so basicly i can use that example ```py
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
i will play around with it and see, thanks @maiden fable
does it throw any error?
nothing happens here tho 😦
now its working
thank you
@maiden fable
thank you for asking @plain shadow
@maiden fablethat timeout seems to be for how long bot is going to wait_for not a timeout for ignore using it
oh i make it simple and stay to commands to prevent API abuse
nope!
this is so dumb. My cog can't use a class from another file.
Can anyone help me
Inport the class from the other file
they can lmao
Why do we need - GUILD PRESENCES INTENT??
@visual drift check this out https://pastebin.com/rJFE9yxq
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
To access things related to presences
thanks
👍
So i have a custom checks and is the custom error that the check raises when it fails:
class WRError(CommandError):
def __init__(self):
super().__init__(message="This user cannot use this command because he doesn't satisfy the necessary "
"requirements")
Now, the problem is that this error doesn't trigger the on_command_error event
how to fix it?
def checkWR_Found():
def predicate(ctx: ApplicationCommandInteraction):
exists = db.field("SELECT DiscordID FROM WildRiftUser WHERE DiscordID IS ?", ctx.author.id)
if exists is not None:
return True
raise WRError
return check(predicate)
This is the check
helo
i have added a cmd in my bot to show the date and time that when the user joined the server using member.joined_at
but how to show the date and time of when they joined discord
New connector on each call?
i'll make it a bot attribute
Still have that issue?
another one
hey is it possible to reply through on_message?
guys what are the ideal domain names for discord bots
sure
reply in the message channel?
also what message are you replying to?
when u do on_message pretty sure u cant use ctx? if im wrong misunderstanding
any message that gets sent to me
yeah it doesnt get a Context object but a Message object, if you want to reply then just await Message.reply(...)
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
huh?
!charinfo 😀
Character Info
\U0001f600: GRINNING FACE - 😀
!source charinfo
Command: charinfo
Shows you information on up to 50 unicode characters.
Source Code
bot/exts/utils/utils.py:51
how can i add http requests in discord.py?
I need help, what's wrong here?```py
def get_prefix(client, msg):
guild = msg.guild.id
list = os.listdir("./data/servers")
if guild in list[:-5]:
with open(f"./data/servers/{guild}.json") as f:
prefixes = json.load(f)
return prefixes[str("prefix")], "$"
else:
return "$"
`./data/servers/serverID.json` ```json
{
"prefix": "!"
}
i don't know sorry
Is there an error?
Is it meant to be a command?
ty
I want to make a command that sends a different message based on the user's id but it said the else function. I tried making a test command with the id function to get the id and see why it isn't working. This is what I got from response: <built-in function id>
How do I fix this?
Can u send code
@bot.command() #The main command I wanted to make
async def data(ctx):
if id == "608575327811272704":
await ctx.reply("Hi VDP")
else:
await ctx.reply("Unknown ID!")
@bot.command() #The test command I made to see the response of *id*
async def test(ctx):
await ctx.reply(id)
Do if ctx.author.id
I asked in stackoverflow.com
What is id. Seems like a function according to the error you got.
The guy told me about user.id but it didn't work so I searched it on the pydocs and found the id just by itself
@bot.command()
async def verificationbutton(ctx):
await ctx.message.delete()
member_role_name = "verified" # role name
user = ctx.author
myembed = discord.Embed(title="VERIFICATION", description="Please click the button bellow to proceed with the verification process!")
await ctx.send(embed=myembed, components = [
[Button(label="VERIFY ME", style="3", emoji = "✅", custom_id="button1")]
])
# button1 reaction
interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
await interaction.send(content = "You have been verified!", ephemeral=True)
await user.add_roles(discord.utils.get(user.guild.roles, name=f"{member_role_name}")) # give verification role
this only allows me to click to button once, even if i remove the verified role from myself after 1 click it says "interaction failed"
And as you got told above, to get the ID of the user who executed the command it's ctx.author.id
So something like that would be more correct
if ctx.author.id == 608575327811272704:
No, IDs are integers not strings.
^
anyone know the cause?
When making a discord dashboard does any one know how do i make the url direct me to the discord login?
Is there a way to get the admin role of a guild if i do Guild.get_role('ADMINISTRATOR)
but theyve changed the role name from administrator to something else will it cause issues?
is it possible to get the role from the guild owner or something?
for dm the response u use
dm_message.on_message()?
But there is-
There surely is
there is on the discordpy page
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
okay but this where?
Here
after the await gives error
You don't seem to define id here
Could you send your current version of code?
here
disnake.ext.commands.errors.ExtensionFailed: Extension 'exts.info.general-info' raised an error: SyntaxError: f-string expression part cannot include a backslash (general-info.py, line 53) ;-;
the problem fixed
Ok so you don't have any issues anymore?
Yeah it can't
so I can remove a part of the code and get working on the other
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Provide instance of this to file param of the send
I have typed this:
@bot.command()
async def data(ctx):
if ctx.author.id == 608575327811272704:
with open("") as file:
await ctx.reply("Your data.")
else:
await ctx.reply("You have not been signed up!")
for a command that only the bot owner can use is it?
@commands.is_owner()
I havent done with the open()
Yeah
@kind wind file is sent like this as far as I remember, haven't used file sending for a while
with open('cool_image.png', 'rb') as f:
await ctx.send(file=discord.File(f))```
Does it have to be in the current folder?
In the folder you are running the main file from yes
You can
That's an absolute path, will work as well
Tho usually all of the project files are put into project's directory
Wdym does it need quotes
say i have the current time stamp how would i add like 10 minutes to that
so if i did the relative dynamic time it would say in 10 minutes
!e
import time
print(time.time())
@dire folio :white_check_mark: Your eval job has completed with return code 0.
1642019121.3838863
nvm got it
i doubt that is a thing
this didnt work
Show your code
You clearly didn't look at my example
^
You forgot open mode and file param
No
Those are actually the same thing
I put " instead of '
!e
print("string" == 'string')```
@vale wing :white_check_mark: Your eval job has completed with return code 0.
True
Yeah but whats the problem
This is the problem
Can you explain it to me please?
I think this example explains it
oh
Open mode is 'rb' which means "read in binary mode"
i understand
File param is file=discord.File(f)
'r' is read
what is the difference with 'rb'?
Up to you, you create a variable here
if i do as f: then i dont have to make variable?
I dont know much of discord.py
The question is how much do you know of python overall
Like do you know OOP (classes, defs, etc.)?
Not much

