#discord-bots

1 messages · Page 745 of 1

slate swan
#
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'```
#
@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

bitter perch
#

your id is probably wrong

slate swan
bitter perch
#

try recopying it and trying again

slate swan
# bitter perch 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'```
#

;-;

bitter perch
#

do you have member intents

slate swan
#
intents = Intents.default()
intents.members = True
#

this one ?

bitter perch
#

well guild.owner is returning none

slate swan
bitter perch
#

please stop ping replying every last message

slate swan
#

oke

#

so how i can solve this

bitter perch
#

what are you doing with that intents object

#

are you passing it to the bot's constructor

slate swan
#

i just want to mention the owner

bitter perch
#

i see that

#

can i have the code when you do ```py
bot = commands.Bot(...)

slate swan
#

quanganh = commands.Bot(command_prefix = '', intents=intents)

bitter perch
#

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

slate swan
#

ok thank you

final pelican
#

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?

cursive barn
#

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

slate swan
#

i recommend you use commands

#

should have a positional argument and typehint it as a member obj

cursive barn
#

this is the best way, but you should understand the error in your logic

jade tartan
#

Is someone experienced with flask?

slate swan
#

#web-development would be a better place for this question ig , unless you are about to ask replit's keep_alive.py

jade tartan
slate swan
jade tartan
slate swan
#

!pypi discord-ext-dashboard

unkempt canyonBOT
slate swan
#

this may be helpful

jade tartan
#

Ok thanks but how do i make the url direct me to the discord login auoth

#

Aouth

jade tartan
slate swan
#

havent tried anything related with that , sorry

vast gale
#

wow 40 minutes without a message here

final iron
#

Not uncommon around these times

vast gale
#

dang

#

its only worth mentioning to me because i heard that this was the most active channel here 😂

final iron
#

Who told you that?

#

This is definitely not the most active channel

vast gale
#

staff lol

final iron
#

¯_(ツ)_/¯

#

Firefox is a god send if you're working with an api

slate swan
#

They probably meant most active help channel

#

Cause general is anyways always active

final iron
#

JSON formatting pithink

vast gale
#

ye

tender estuary
final iron
vast gale
#

or on the cmd line: python -m discord -v

tender estuary
#

is 1.7.3 rewrite?

vast gale
#

wdym?

tender estuary
vast gale
#

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

crisp bloom
#

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

hot cobalt
#

You have break before the send

#

break ends the loop immediately

#

So that send will never be reached

slate swan
#

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.

hot cobalt
#

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

spring flax
#
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]?

pliant gulch
#

Yea was about to say why you closing the pointer and right after reading from it

vast gale
#

and no check for the message to be sent from the author

hot cobalt
vast gale
#

you'd need to make it an instance method attached to a messegable instance

spring flax
hot cobalt
#

You've already done that

spring flax
#

Right now, I do await send(ctx, message="my message")

vast gale
#

they both work

hot cobalt
#

You can just do await send(ctx, "my message")

#

Either way will work

spring flax
#

oh...i thought I tried it but it raised an error let me see

hot cobalt
#

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

untold token
hot cobalt
untold token
vast gale
untold token
#

and can you send me the entire code

vast gale
#

although often I set defaults and other kwargs

untold token
#

and don't use replit for hosting discord bots

vast gale
#

so it ends up being a custom send method which adds an embed and other things :)

spring flax
vast gale
untold token
#

That's the job for ya

vast gale
#

nO

untold token
#

I will send the code and you will compile it

#

yEs

slate swan
#

lmao why does this even exist

pliant gulch
cedar dragon
pliant gulch
slate swan
#

^

pliant gulch
#

Who even asks for this lmao

slate swan
#

discord is 13+ already

pliant gulch
#

this is the most dumbest idea I've seen in a few motnhs

slate swan
#

I would firstly inform yourself before sending some links with laws and everything.

vast gale
#

in related news mee6 is shit

vast gale
#

(mee6 has a bday feature)

slate swan
#

yea

untold token
#

Lol

vast gale
#

mee6 also has an nft feature

cedar dragon
#

Well, I'd consider the year to be too sensitive

vast gale
untold token
#

Mee6 logs stuff too

slate swan
#

Again, it's with consent.

quick gust
cedar dragon
#

Okay I get it

untold token
slate swan
#

Read the Discord's developer policy, privacy policy and terms of service.

cedar dragon
untold token
#

Hello krypton

quick gust
vast gale
#

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...

quick gust
#

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

pliant gulch
final iron
#

Why do bots gate custom commands

#

They're so incredibly easy to make

pliant gulch
#

Same reason why Marak trolled color.js

#

OSS is hard to make money from!

final iron
#

Literally have no idea what you're talking about

#

🏃

cedar dragon
#

But other people might want to make money off FOSS/OSS/free software/open source

zealous dagger
final iron
#

Oh, open source software

zealous dagger
pliant gulch
final iron
#

So they don't clog up the help channels

cedar dragon
#

So I don't know what it's like to be a maintainer of a big project

pliant gulch
#

Maintained 2 ish med projects and 1 big project

#

Very stressful

cedar dragon
#

I mostly just submit patches

pliant gulch
#

The code part wasn't even that stressful, it was the contributors lmao

cedar dragon
#

Did any of them use.. offensive language?

pliant gulch
#

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

final iron
cedar dragon
#

What is it that they don't like about their team

tender estuary
final iron
pliant gulch
final iron
#

Like really chaotic

pliant gulch
#

😔

cedar dragon
pliant gulch
#

Got a new private repo where my rework is, very radically different

cedar dragon
#

Nice Discord API wrapper

pliant gulch
#

I don't really like it as it is right now

desert heart
#

Contributing is fun. Maintaining, not so much. Some people tend to feel too entitled.

pliant gulch
#

And that's mostly because I copied a lot of the semantics

cedar dragon
#

Well, I'm more of a C/C++ dev, not sure if I can rate your Python code properly..

pliant gulch
slate swan
tender estuary
#

I picked python in 2018 I guess.

#

Then left it ofc

slate swan
#

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

slate swan
tender estuary
slate swan
vast gale
vast gale
#

and yet you know more than me 🤡

slate swan
final iron
#

He sweats discord bots

slate swan
final iron
#

Okay I sleep now

valid galleon
#

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?

slate swan
slate swan
valid galleon
#

alright, thanks for helping

slate swan
#

For me, I have been coding bots for at least 3-4 years

tender estuary
#

dayum

slate swan
#

I remember the migration of discord.py 0.16.x to 1.x thisisfine

#

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 :)

slate swan
#

People said I would never be happy, get a girlfriend and have a good job. And here I am, having all of this KryptonBlanket

#

So you will without a doubt achieve it ^^ Not having experience in Discord bots doesn't prove anything.

pliant gulch
slate swan
#

wow you guys deserve the verified bot dev badge :))

#

That was the good old times ^^

slate swan
#

Just some pixels on my profile, doesn't really matter

slate swan
pliant gulch
slate swan
#

dang thats really oldpithink

#

Yeah

#

You can probably find old forks

#
client = discord.Client()
client.login("email", "password")
client.run()
#

Was something like that

#

wowyert

desert heart
#

That was surely longer than 3-4 years ago

cedar dragon
#

👀

slate swan
#

Yeah that was longer, I however got into really programming a bot 3-4 years ago.

desert heart
#

That was probably like 2016 I'm guessing

slate swan
#

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.

pliant gulch
#

Danm 6 years went past crazy fast

#

Remember when I signed up for discord right at late 2015

slate swan
#

Old forks probably still have commit dates.

#

Anyways, I got to work on my projects; have a great day and see you later ^^

pliant gulch
#

Lost the old one sadly

spring flax
#

What happepend?

pliant gulch
#

Just abandoned

#

No longer have the email to the account nor the password as I've transferred to protonmail from gmail

cedar plank
#

hey whats wrong

hot cobalt
#

Chances are the issue is on the line above

cedar plank
#

nice

#

ty

spring verge
#

has anyone used heroku?

#

if yes how did u use env variables.. did u push the env file to your github repo?

oblique adder
#

how do I use ctx.invoke in on_message event ?

slate swan
#

You need to use bot.get_context

#

To get a Context object variable

oblique adder
#

bot.get_context(message , cls=cls) ?

slate swan
#

!d discord.ext.commands.Bot.get_context

unkempt canyonBOT
#

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").
slate swan
#

Without cls=cls

#

That's not needed in your case.

oblique adder
slate swan
#

As I said, you need to await it.

slate swan
#

No you didn't.

#

Correct would be
await bot.get_context....

slate swan
#

And why are you using once self.bot and once just bot?

oblique adder
#

changed

slate swan
#

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.

oblique adder
#

how do i check if it is valid ?

slate swan
#

The returned context is not guaranteed to be a valid invocation context, 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().

#

It's just a matter of reading the documentation :)

oblique adder
#
ctx  =await self.bot.get_context(message)
if ctx.valid:
   await ctx.invoke(self.bot.get_command(commandname), args='whatever')```
slate swan
#

Seems good to me

oblique adder
#

ok thanks

pliant gulch
#

The last line doesn't look right to me

oblique adder
#

which line ?

slate swan
#

Oh yeah

#

The args go after get_command.

#

Now that's better.

oblique adder
slate swan
#

Considering the command name and the arguments are correct, yes.

oblique adder
spring verge
#

any host recommendations for discord bots?

vale wing
#

Also check pins

spring verge
#

oh the vps pin?

vale wing
#

Yeah

#

I checked them all turns out the galaxygate is the best option but it is up to you what to choose

spring verge
#

ohh well Imma check out galaxygate thx

spring verge
vale wing
#

Totally

slate swan
#

yes 1gb of ram is overkill ngl

spring verge
#

oh

vale wing
#

I have several bots on that server and one is at > 100 guilds

#

Works fine

spring verge
#

okay thx

slate swan
vale wing
#

If you need help with server setup feel free to ask me because it might be difficult to figure out

vale wing
vale wing
#

Yeah

slate swan
slate swan
vale wing
#

I wonder how to run bot in docker thinkmon

#

Omg no way my nitro expired and I got a nice tag

slate swan
slate swan
#

i just wanted to know the average of it

#

There's no average, depends who you ask.

slate swan
#

4GB is the bare minimum in my opinion.

slate swan
pliant gulch
slate swan
#

How can the bot get access to cached things without listening to them.

pliant gulch
#

bot.get_

slate swan
#

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?

pliant gulch
#

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

slate swan
#

You won't get cached all messages if you don't listen to the events accordingly, example for the on_raw_reaction_add.

pliant gulch
#

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

slate swan
#

Wait, I meant intents, not events.

#

If you disable not needed intents, you don't get any of the events.

pliant gulch
#

Sure, if you disabled member intents that would significantly cut the memory usage

#

As both member cache and user cache depend on it

slate swan
#

Yeah, I confused events and intents; my bad ^^

#

can you guys keep talking about cache im learning allotpithink

primal cliff
#

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

vale wing
#

!d discord.on_member_update

unkempt canyonBOT
#

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...
vale wing
slate swan
#

Why isn't this working?
It isn't even showing an error

vale wing
#

How do you define client

#

Also this method of comparing channel type is not good

#

Use either == operator or isinstance

slate swan
#

How do I give default permission to user in a specific channel?

vale wing
#

To set permissions for the channel there's this

#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

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...
slate swan
untold token
#

Yes it is

#

message.content returns the contents of the message as an str

slate swan
#

yeah

untold token
maiden fable
#

@untold token yk, not everyone is as well versed as u, with docker containers lol

vale wing
untold token
#

You can reference docker documentation to create your own docker container image and run it

vale wing
#

But I know how to do all that I only need to figure out where does the docker run the file

untold token
#

That channel is dormant

vale wing
#

Answer it here or in dms if possible

spring flax
#

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

vale wing
#

All I need is basically where does docker start running

untold token
#

Sure, if you want to do it in dms, docker containers is outside the topic of this channel anyways

vale wing
#

Yeah

spring flax
#

was it tested?

#

Because I asked before and I am getting mixed responses

primal cliff
#

oh ok and how to make the bot only response to admins/mods

spring flax
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@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")
maiden fable
spring flax
primal cliff
spring flax
#

like only respond to users with manage messages permissions

#

that?

primal cliff
spring flax
primal cliff
#

role or role id

spring flax
#

is the bot only in one server? or is the command you're talking about only being used by one server?

spring flax
primal cliff
spring flax
#

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

maiden fable
#

@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 (:

green bluff
#

unbans r not working

placid skiff
#

user.discriminat is not a user paramater

green bluff
#

so

#

is it user.discriminate

spring flax
#

don't unban a member like that.

placid skiff
#

is discriminator .-. like for member

green bluff
#

oh ok

#

also

#

can i change member.name and member.discriminator to member.split

#

wait wdym

#

dont unban like that

spring flax
#

@green bluff That is a very ineffective way to do it. I assume you are watching lucas.

placid skiff
spring flax
#

!d discord.Object

unkempt canyonBOT
#

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.
mild zephyr
#

hawwo! i was wondering if i can set to a variable, a type like "a list of roles"

spring flax
#

Use this to get the member object with the given ID, and call Guild.unban on the discord object (which is a member)

spring flax
#

!d discord.User

unkempt canyonBOT
#

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.
brazen raft
#

Or something like that

#

Depends on your library

spring flax
#

you can use greedy for that as well, I believe

brazen raft
#

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

mild zephyr
# spring flax what do you mean?
    @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'")

brazen raft
green bluff
#

something like this?

placid skiff
green bluff
#

or i dont understand

brazen raft
mild zephyr
green bluff
#

oh yea user is a variable

#

no i mean member

#

do i just do guild.unban(member)

placid skiff
#

both member and user in your code are variables D_D

green bluff
#

o ya

spring flax
#

what is listname supposed to be for?

mild zephyr
#

for dropdowns

spring flax
mild zephyr
spring flax
#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

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`...
mild zephyr
#

doesnt recognize "greedy"

spring flax
#

imports

mild zephyr
spring flax
#

you're using disnake

#

!d disnake.ext.commands.Greedy

unkempt canyonBOT
#

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`...
spring flax
#

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

tender estuary
#
@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?
tender estuary
#

And stupid replit won't tell me where the error is.

spring flax
#

do you have an error handler?

tender estuary
#

yes

spring flax
mild zephyr
# spring flax which is?

ExtensionFailed("Extension 'exts.rolelist' raised an error: TypeError: unhashable type: 'Greedy'")

mild zephyr
maiden fable
#

Why u tryna write the Greedy class to a text file

spring flax
#

the full command

spring flax
maiden fable
#

That error comes when an object is being written into a text file or smth but Python fails iirc

spring flax
#

yeah, a database too

mild zephyr
#
async def add(self, inter: disnake.CommandInteraction, listname:str, roles: Greedy[discord.Role]):
    print(roles)
    pass
spring flax
#

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?

mild zephyr
#

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

spring flax
#

what do you want to do with the list of roles?

#

get their id's?

mild zephyr
#

i can get this

#

but not list of roles

#

here i'm forcing the input only as specific thing with autocomplete

spring flax
#

ah slash commands

#

i've never used those before, so i wouldn't know

slate swan
#

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?

vale wing
#

@mild zephyr discord API doesn't support mutliple values for one argument afaik

placid skiff
vale wing
#

Unless you create custom converter

mild zephyr
mild zephyr
placid skiff
#

disnake actually let you use typehints for slash commands

spring flax
#

!d discord.ext.commands.Greedy @vale wing

unkempt canyonBOT
#

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`...
placid skiff
#

then what is your problem? xD

mild zephyr
#

if i wanna ad 20 roles to a list it would be painfull to get a one at one

sullen pewter
#

where do people learn how to code bots?

mild zephyr
sullen pewter
#

k

placid skiff
placid skiff
#

Guys my PyCharm doesn't recognize intellisense for disnake, why? i allways used it and it allways worked fine

slate swan
#

how do I give default permission to user for accessing a private channel after creating a new channel?

keen talon
#

Sup Bois

proper acorn
#

help me please

jade tartan
#

When making a discord dashboard does any one know how do i make the url direct me to the discord login?

jade tartan
keen talon
unkempt canyonBOT
#

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.

jade tartan
proper acorn
#

#replit

vale wing
# spring flax it does

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.

spring flax
slate swan
#

After creating a private channel how do I give access to specific users?

tender estuary
quick gust
tender estuary
#

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.

quick gust
#

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

prime marten
#

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?

tender estuary
prime marten
#

damn :/

placid skiff
#

Can I send in slash command interaction an embed with an ephemeral message?

quick gust
#

Yeah

placid skiff
#

And fields index in embeds starts from 0 right?

quick gust
#

Not too sure

small igloo
#

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']
dreamy sluice
#

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 ![lel](https://cdn.discordapp.com/emojis/926461435444338758.webp?size=128 "lel")")
        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']} ![floofbred](https://cdn.discordapp.com/emojis/928880102014590996.webp?size=128 "floofbred")", value="")
              if e["sellable"] is False:
                embed2.add_field(name="_Cannot be sold._", value="")
              else:
                embed2.add_field(name=f"Sell- {e['sell_cost']} ![floofbred](https://cdn.discordapp.com/emojis/928880102014590996.webp?size=128 "floofbred")", value="")
            await ctx.reply(embed=embed2)
#

The last statement is the one which isn't executing btw*

slate swan
#

the embed sending part?

dreamy sluice
#

That's not working for some reason.

slate swan
#

any errors?

dreamy sluice
#

It doesn't return any

slate swan
#

the json files may be empty..

dreamy sluice
vale wing
dreamy sluice
slate swan
#

it would have not done those steps already py for i in read1:

#

if read1 is empty it wont process

dreamy sluice
#

I checked everything (with loads of print statements), and only the embed line isn't executing

vale wing
#

Oh yeah

dreamy sluice
#

The last one, I mean

vale wing
#

@dreamy sluice try printing embed2.to_dict()

vale wing
#

Also do you get any errors

dreamy sluice
#

it returned the contents of the embed

#
{'fields': [{'inline': True, 'name': '_Cannot be bought._', 'value': ''}, {'inline': True, 'name': 'Sell- 20 ![floofbred](https://cdn.discordapp.com/emojis/928880102014590996.webp?size=128 "floofbred")', 'value': ''}], 'color': 2069990, 'type': 'rich', 'description': 'A smol, insolent bug. Can be sold for 20 ![floofbred](https://cdn.discordapp.com/emojis/928880102014590996.webp?size=128 "floofbred")\n_(Short-tbug)_', 'title': 'Smol Beetle  (1 owned)'}
vale wing
#

Hm right

#

You printed it right before the reply?

dreamy sluice
#

Ye

vale wing
#

Do you have error handlers

dreamy sluice
#

Nope

vale wing
#

Try to send something other than embed

slate swan
#

the value is empty

#

its a 0 length string

dreamy sluice
vale wing
#

@slate swan description is not empty

dreamy sluice
vale wing
#

Ik but it is not why it doesn't work

dreamy sluice
#

O-o

vale wing
slate swan
#

lemme send an example

dreamy sluice
vale wing
#

I know what that is

#

I don't understand why do you send that, do you think it is not sending because of this?

dreamy sluice
#

It just doesn't send the embed

vale wing
#

Anyways if it was because of embed it would most likely raise bad request

slate swan
#

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

vale wing
#

Yeah but he gets no exceptions

slate swan
#

maybe they have an error handler

dreamy sluice
slate swan
#

no on_command_error event?

vale wing
#

@dreamy sluice anyways try to do what they suggested

dreamy sluice
vale wing
#

Ah

slate swan
#

thats what an error handler is:p

dreamy sluice
#

ok I am dum

#

:(

vale wing
#

You should raise all unknown exceptions in it or print them

slate swan
#

add else : raise error in the end , it helps u to get untraced errors

dreamy sluice
#

mkay

slate swan
#

considering error to be the variable for your exception

dreamy sluice
#

lemme try

#

OK, it returned the error you mentioned @slate swan

slate swan
#

set an value for the field

#

if you dont want to set one , use \u200b there

dreamy sluice
#

:o

#

Thanks a lot

#

It works

oak warren
#

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
slate swan
#

You respond twice if one of your if checks is successful.

#

You also need to return when sending the message in your if checks.

oak warren
#

i do return

#

the last line

oak warren
slate swan
#

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.

oak warren
jovial plover
spring flax
#

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?

slim ibex
#

are they both in the same folder

placid skiff
#

Guys in embeds fields index starts from 0 or 1?

visual island
#

0

slim ibex
#

all indexs start from 0

vale wing
#

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

vale wing
jovial plover
#

Whats the official import module for discord buttons

vale wing
#

Dpy 2.0 supports it but it is no longer maintained

slim ibex
#

use nextcord

vale wing
#

You could use fork, I don't really think you need official library

slim ibex
#

!pypi nextcord

unkempt canyonBOT
slim ibex
#

ooo a6

vale wing
#

Nextcord, pycord, disnake - any of them

hoary cargo
#

!pypi disnake

unkempt canyonBOT
slim ibex
#

!pypi pincer

unkempt canyonBOT
spring flax
vale wing
vale wing
#

And from what cog to which do you want them to import to

spring flax
#

From the functions cog to the utility cog

vale wing
#
from cogs.functions import ...```
spring flax
#

Isn't there any way to auto import them?

vale wing
#

Like?

#

With *?

spring flax
#

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

vale wing
#

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

spring flax
vale wing
#

I dunno, it shows up for me tho I didn't edit any settings like that

slim ibex
#

can’t you do from . import functions

#

or .functions import …

spring flax
vale wing
sick wedge
#

dc.py can make a axie tracker? like can track the total slp of a user etc..?

slim ibex
#

ik and we know what happens there

vale wing
#

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

vale wing
#

Not counting the AI assistant it doesn't suggest autoimport

slate swan
#

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

honest vessel
#
<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 \⚫
slate swan
#

whats the emoji name on discord?

#

honest vessel
#

black_circle

#

but i use the \⚫

#

its same

slate swan
#

try typing it out like :black_circle:

honest vessel
#

it should be like emoji=<PartialEmoji animated=False name='\⚫'

vagrant brook
#

it's just font problem

#

don't worry lmao

honest vessel
#

well i cant grab it i want to check if the emoji used is in a list

#

or a dict to be more specific

honest vessel
#

@vagrant brookthanks ur were correct

scenic viper
#

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!

slate swan
# scenic viper Hello, everyone! I would like some advice, please, on which Python package to u...

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
scenic viper
quaint epoch
#

I finally got to use my mod bot

quaint epoch
bitter perch
slate swan
#

unless u install it as discord

bitter perch
#

Yes it does

#

I see a namespace rename on this GitHub

slate swan
#

Well Disnake does not do that.. ```bash
$pip install disnake[discord]

quaint epoch
#

or the bytes version of it

scenic viper
#

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!

tough lance
#

!charinfo ⚫

unkempt canyonBOT
scenic viper
#

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.

maiden fable
#

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

honest vessel
#

is there a way to limit reactions to 1 in same message or timeout on reactions ?

scenic viper
maiden fable
slate swan
maiden fable
#

Damn seems like hikari is getting more popular pithink

scenic viper
slate swan
unkempt canyonBOT
#

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.
slate swan
#

And hushhh , lucas with a hikari series now

maiden fable
slate swan
#

Imagine ban command in hikari

maiden fable
#

Lmaooo

slate swan
#

Wait lemme copy paste it , someone sent it recently

maiden fable
#

Not there 🥲

grim oar
#

Hikari kinda gud

tough lance
#

I've expired form making discord bots WutStare

maiden fable
#

Same

#

I have stopped deving discord bots

tough lance
#

I've only used disnake since the discord.py shut down so I won't give any opinions on this

scenic viper
#

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?

maiden fable
#

Yea, disnake is a bit more stable, with faster feature releases and better updates

quaint epoch
maiden fable
#

Can't happen

quaint epoch
quaint epoch
#

15 times

maiden fable
#

Ping depends on your network connection, not the library

quaint epoch
maiden fable
#

Even @slate swan can confirm that

quaint epoch
#

but i prefer disnake

#

because reasons

tawdry perch
slate swan
maiden fable
maiden fable
slate swan
#

and the code implications for that is same , atleast for all the forks

slate swan
maiden fable
#

Thanks

rare saddle
#

Someone can explain why these intentions are needed and how to correctly request from Discord access for a verified bot

quaint epoch
maiden fable
#

When u fill the form for verification of the bot, u need to fill in the intents u need, with a valid use case

quaint epoch
#

too lazy to specify

#

(intents in code)

maiden fable
rare saddle
quaint epoch
maiden fable
rare saddle
maiden fable
rare saddle
maiden fable
#

That means u can use fetch_member without using the intent

#

!d discord.Guild.fetch_member

unkempt canyonBOT
#

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.
rare saddle
# rare saddle

But the bot cannot be added to more than 100 servers, and I suppose that because of this

#

and

maiden fable
#

Huh?

#

Mind giving me your Bot name/invite link in DMs?

#

Wait no...

rare saddle
maiden fable
#

It's verified... It should be able to be added to more than a 100 guilds

rare saddle
#

Can I somehow enable this without asking for permissions from Discrd? Verified bot

tender estuary
#

is it a good idea to leave discord.py because it got shutdown or ?

quaint epoch
#

like hikari, disnake, pycord and more

#

but it's your choice lol

tender estuary
#

Which one's the best in your opinion

polar ice
#
            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?

slate swan
spring flax
polar ice
#

@spring flaxTo get the default role in the guild?

spring flax
polar ice
#

@spring flax 😮

spring flax
#

it's discord.Guild.defaul_role.
You need a guild object.

polar ice
#

Silly me, thanks 😄

spring flax
#

By using guild.id, you are not working with a guild object

polar ice
spring flax
#

haha lol it happens

visual drift
#

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

slate swan
#

(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```
visual drift
#

try to debug this program (for example on the first line type print(user))

slate swan
#

oh okay

#

i think i just dont have the table lmao

visual drift
#

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

slate swan
#

its fine thanks

slate swan
visual drift
#

examples??

slate swan
#

"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?

honest vessel
#

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
#

@arctic python can you help?

#

sorry fot the pings

honest vessel
#

no need to ping all dood 😄

slate swan
#

ikik

honest vessel
#

@slate swan app.run() is never being runned.

honest vessel
#

cause its in namespace __main__

slate swan
#

what should i change?

honest vessel
#

prob just remove if __name__ == "__main__":

maiden fable
slate swan
#

didn't happen

maiden fable
#

What's the issue?

honest vessel
#

I dont know, its not a cog either

slate swan
#

to get my bot guild count

maiden fable
#

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

slate swan
#

k

honest vessel
#

@maiden fableany idea of my Q?

maiden fable
#

What's the q

slate swan
honest vessel
#

a way to make timeout for reactions per user or so?

slate swan
#

will that work?

plain shadow
#

idk

honest vessel
#

was thinking of something builtin

tawdry perch
#

So you want to block user from reacting for x duration?

maiden fable
#

There's nothing in built for that... Instead u can use bot.wait_for

honest vessel
#

yeah so they cant just spam the emoji and abuse API both themself and bot that gives them roles/removes

tawdry perch
#

Temporary role that don't allow reacting?

maiden fable
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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**...
slate swan
#

what should i do?

honest vessel
#

i will play around with it and see, thanks @maiden fable

plain shadow
honest vessel
#

nothing happens here tho 😦

slate swan
#

thank you

#

@maiden fable

#

thank you for asking @plain shadow

honest vessel
#

@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

plain shadow
humble granite
#

this is so dumb. My cog can't use a class from another file.
Can anyone help me

boreal ravine
rare saddle
#

Why do we need - GUILD PRESENCES INTENT??

slate swan
boreal ravine
rare saddle
boreal ravine
#

👍

placid skiff
#

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

stable berry
#

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

cloud dawn
#

New connector on each call?

slate swan
#

i'll make it a bot attribute

cloud dawn
slate swan
#

hey is it possible to reply through on_message?

crisp shoal
#

guys what are the ideal domain names for discord bots

spring flax
#

reply in the message channel?

slate swan
#

ill found a way

spring flax
#

also what message are you replying to?

slate swan
#

when u do on_message pretty sure u cant use ctx? if im wrong misunderstanding

#

any message that gets sent to me

grim oar
#

!d discord.Message.reply

unkempt canyonBOT
#

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.
slate swan
#

hey folks, real quick, how do I access my bots user ID? client.id failed

cloud dawn
#

!charinfo 😀

unkempt canyonBOT
cloud dawn
#

!source charinfo

unkempt canyonBOT
#
Command: charinfo

Shows you information on up to 50 unicode characters.

Source Code
slate swan
#

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

slate swan
#

but it isnt working too

dire folio
#

Is it meant to be a command?

kind wind
#

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?

dire folio
#

Can u send code

kind wind
#
@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)
dire folio
#

Do if ctx.author.id

kind wind
slate swan
#

What is id. Seems like a function according to the error you got.

kind wind
#

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

slate swan
#
@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:
kind wind
#

wouldnt it be with ""?

#

oh yeah its an int not a str

slate swan
#

No, IDs are integers not strings.

dire folio
#

^

jade tartan
#

When making a discord dashboard does any one know how do i make the url direct me to the discord login?

polar ice
#

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?

kind wind
#

for dm the response u use
dm_message.on_message()?

#

But there is-

#

There surely is

#

there is on the discordpy page

vale wing
#

!d discord.User.send

unkempt canyonBOT
#

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**.
kind wind
#

okay but this where?

vale wing
kind wind
#

after the await gives error

kind wind
#

dm*

vale wing
kind wind
#

Yeah I fixed that

#

with ctx.author.id

vale wing
#

Could you send your current version of code?

cloud dawn
#

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) ;-;

kind wind
#

the problem fixed

vale wing
#

Ok so you don't have any issues anymore?

kind wind
#

With that no. But I want to dm the user a file

#

I just used that for test

kind wind
#

so I can remove a part of the code and get working on the other

vale wing
#

!d discord.File

unkempt canyonBOT
#

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.
vale wing
#

Provide instance of this to file param of the send

kind wind
#

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!")
dire folio
#

for a command that only the bot owner can use is it?

@commands.is_owner()
kind wind
#

I havent done with the open()

vale wing
#

@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))```
kind wind
#

Does it have to be in the current folder?

vale wing
#

In the folder you are running the main file from yes

kind wind
#

Oh no...

#

Can't I like

#

Use the entire thing

#

Like from C:\Users\etc.

vale wing
#

You can

#

That's an absolute path, will work as well

#

Tho usually all of the project files are put into project's directory

kind wind
#

So I need to get the txt files out of the usb

#

Does it need "" or not?

vale wing
#

Wdym does it need quotes

kind wind
#

Like the path

#

Does it need quotes between them?

vale wing
#

All string objects are put in quotes, path is a string

#

So obviously it does

kind wind
#

Like:
"C:\Users\"

#

okay

dire folio
#

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())
unkempt canyonBOT
#

@dire folio :white_check_mark: Your eval job has completed with return code 0.

1642019121.3838863
dire folio
#

i doubt that is a thing

kind wind
vale wing
kind wind
vale wing
#

You clearly didn't look at my example

kind wind
#

Oh-

#

I said ""

#

Not ' '

vale wing
#

You forgot open mode and file param

kind wind
#

No

vale wing
kind wind
#

I put " instead of '

vale wing
#

!e

print("string" == 'string')```
unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

True
kind wind
#

Yeah but whats the problem

vale wing
kind wind
#

Can you explain it to me please?

vale wing
kind wind
#

oh

vale wing
#

Open mode is 'rb' which means "read in binary mode"

kind wind
#

i understand

vale wing
#

File param is file=discord.File(f)

kind wind
#

'r' is read
what is the difference with 'rb'?

vale wing
#

Binary mode

#

discord.File requires binary

kind wind
#

I mean whats the difference on the output

#

ok

#

as f: or as file:

vale wing
#

Up to you, you create a variable here

kind wind
#

if i do as f: then i dont have to make variable?

vale wing
#

f will be your variable?

#

Could I ask when did you start learning python

kind wind
vale wing
#

The question is how much do you know of python overall

kind wind
#

Not very very much

#

I recently bought a guide for python

vale wing
#

Like do you know OOP (classes, defs, etc.)?

kind wind
#

Not much