#discord-bots

1 messages Β· Page 575 of 1

slate swan
#

-_-

unkempt canyonBOT
#

property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.
slate swan
#

same way as channels

#

Thanks

steady flume
#

@vapid trellis @slate swan @slate swan DONE!

urban shell
#

try something like this -

split = list(text)
i = len(split)
l = []
for j in range(0, i):
    spoiler = "|" + split[j] + "|"
    l.append(spoiler)
s = ''.join(l)
await ctx.send(s)
steady flume
#
    async def spoiler_cmd(self, ctx, *, text=None):
        if text is None:
            await ctx.reply("What do you want me to say?", mention_author=True)
        else:
            parsed_args = "||||".join(text)
            await ctx.send(f"||{parsed_args}||")
slate swan
#

Great but dont ping us some people dont like it

steady flume
#

i wont

vapid trellis
steady flume
slate swan
vapid trellis
#

glad it works

urban shell
#

nice

#

Gg

steady flume
#

ty bro

slate swan
#

why am i getting this error;

Traceback (most recent call last):
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\coolb\OneDrive\Documents\mootbot\cogs\Commands.py", line 337, in resetcooldown
    await partner.reset_cooldown(ctx)
NameError: name 'partner' is not defined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\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: NameError: name 'partner' is not defined

when i run this command

    @commands.command(name="resetcooldown")
    @commands.has_any_role("Staff")
    async def resetcooldown(self,ctx,member: discord.Member=None):
        await partner.reset_cooldown(ctx)
        await ctx.send("Reset")```

in reference to this command:

```py
    @commands.command(name="partner")
    @commands.cooldown(1, 21600, commands.BucketType.user)
    async def partner(self,ctx,member: discord.Member=None):```
dapper cobalt
slate swan
# dapper cobalt It would be `await self.partner()`.

as in

    @commands.command(name="resetcooldown")
    @commands.has_any_role("Queer")
    async def resetcooldown(self,ctx,member: discord.Member=None):
        await self.partner.reset_cooldown(ctx)
        await ctx.send("Reset")```
#

?

manic wing
#

correct.

slate swan
#

gives me

Traceback (most recent call last):
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\coolb\OneDrive\Documents\mootbot\cogs\Commands.py", line 337, in resetcooldown
    await self.partner.reset_cooldown(ctx)
TypeError: object NoneType can't be used in 'await' expression

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\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: TypeError: object NoneType can't be used in 'await' expression
urban shell
#

hey guys, so I have been trying to retrieve the member info using this command -
member = discord.utils.get(guild.members, name="KamiKaizen")
but I was wondering if I could do the same with the member id instead of the member name
or is there a way to retrieve the member name if the id is known

vapid trellis
urban shell
queen summit
#

dont, thats an api call

vapid trellis
queen summit
#

and takes a long time

#

compared to other solutions

vapid trellis
#

oh, I see. I didnt know about that

urban shell
#

Ooof

#

thanks for the warning

queen summit
#

what are you trying to do

vapid trellis
queen summit
#

use a typehint

maiden fable
unkempt canyonBOT
queen summit
#

can work but not recommended

#

@urban shell is this a user info type command?

maiden fable
#

Ah, well yes. If its a command, typehinting is the best way

urban shell
# queen summit what are you trying to do

what I'm trying to do is alter the vc permissions, something like -

m = discord.utils.get(guild.members, name="KamiKaizen")
vn = discord.utils.get(guild.channels, id=f)
await vn.set_permissions(m, connect=True)
queen summit
#

show your whole code

#

of that cmd/func

urban shell
maiden fable
#

!d discord.Client.get_guild

unkempt canyonBOT
vapid trellis
#

@urban shellis it a command or a seperate function??

queen summit
#

not literally discord.Guild an instance, most common is ctx.guild

#

and mising req arg of 'self' means this is in a cog and you didnt add it

vapid trellis
urban shell
queen summit
#

all of this is revolving around us asking your code and you still not giving it and not giving any details

queen summit
urban shell
#

I used guild = message.guild

#

to fetch the guild

queen summit
#

works

vapid trellis
maiden fable
#

That error is coming cz it's not a classmethod but an instance method

queen summit
#

or class but dont think so depending on question

steady flume
#

how i can call attribute for ! and ? ??

toxic flint
#

Are there any community standards for packaging plugins for discord?

slate swan
#

    @commands.command(name="Reset")
    @commands.has_any_role("Reset")
    async def reset(self,ctx):
        await ctx.message.delete()
        self.partner.reset_cooldown(ctx)
        self.nitropartner.reset_cooldown(ctx)
        self.staffpartner.reset_cooldown(ctx)
        await ctx.send("Your cooldown has been reset!", delete_after=5)
        resetrole = discord.utils.get(ctx.guild.roles, name="Reset")
        await ctx.author.remove_roles(resetrole)

how can i turn this command into something where you do -reset @slate swan and it would reset @slate swan 's cooldown?

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
kindred epoch
#

first type hint it and then use it as an arg

pine lava
#

if reaction.emoji == "βœ…":
would that work?
and reaction is defined from the wait for

kindred epoch
#

yes

#

and if not, then convert reaction.emoji to a str

pine lava
pine lava
#
        if str(reaction.emoji) == "βœ…":
            await ctx.reply(f"{ctx.author.display_name}, {user.display_name} agrees to duel with you!")
        if str(reaction.emoji) == "❌":
            await ctx.reply(f"{ctx.author.display_name}, {user.display_name} does not want to duel!")```
#

thats my code and there is no error

kindred epoch
#

show ur whole code

pine lava
#
        def ucheck(reaction, user):
            return user == user and reaction.message.channel == ctx.channel

        a = await ctx.send(f"{user.mention}, do you accept this duel for {amount} :zcoin:?")
        await a.add_reaction("βœ…")
        await a.add_reaction("❌")
        reaction, user = await self.bot.wait_for('reaction_add', timeout = 60, check=ucheck)
        if str(reaction.emoji) == "βœ…":
            await ctx.reply(f"{ctx.author.display_name}, {user.display_name} agrees to duel with you!")
        if str(reaction.emoji) == "❌":
            await ctx.reply(f"{ctx.author.display_name}, {user.display_name} does not want to duel!")```
kindred epoch
#

whole code

pine lava
#

ok

#
    async def duel(self, ctx, user: discord.Member, amount: int):
        users = await self.get_bank_data()
        u = ctx.author

        def ucheck(reaction, user):
            return user == user and reaction.message.channel == ctx.channel

        a = await ctx.send(f"{user.mention}, do you accept this duel for {amount} :zcoin:?")
        await a.add_reaction("βœ…")
        await a.add_reaction("❌")
        reaction, user = await self.bot.wait_for('reaction_add', timeout = 60, check=ucheck)
        if str(reaction.emoji) == "βœ…":
            await ctx.reply(f"{ctx.author.display_name}, {user.display_name} agrees to duel with you!")
        if str(reaction.emoji) == "❌":
            await ctx.reply(f"{ctx.author.display_name}, {user.display_name} does not want to duel!")```
pine lava
kindred epoch
#

ye

pine lava
#

k

kindred epoch
#

try changing ur type hint of discord.Member to member

pine lava
#

k

pine lava
hollow shale
#
await ctx.send(f"Click [here]({link}) ")```
why doesnt it work? i want it to be clickable
kindred epoch
slate swan
#
@bot.command()
async def st(ctx, *, user : discord.Member):
    message = await ctx.send(user.public_flags)
    if 64 in message:
        await message.edit('Bravery')```
#

how am i meant to do this?

kindred epoch
slate swan
kindred epoch
#

ye

#

no

#

where did value come from

slate swan
#

thats the output for line 3

kindred epoch
#

ik, im not asking about the output, im asking where did value come from

slate swan
#

thats what it says when u use

@bot.command()
async def st(ctx, *, user : discord.Member):
    await ctx.send(user.public_flags)```
#

well for me, considering my flag is bravery

kindred epoch
#

the code does not know where value is, so you need to define it

slate swan
#

so 64 = bravery

kindred epoch
#

i said value is an attribute of public_flags

#

do you know what an attribute is?

slate swan
#

thats like

#

Members is an attribute of discord.Members

#

right?

kindred epoch
#

no

slate swan
#

when it comes down to the proper names of things i kinda lose my head lol

kindred epoch
#

thats not supposed to happen

#

attributes is like one of the basic things you learn first

#

then how would you not know what that is/means

slate swan
#

otherwise ive developed everything ive ever done off the top of my mind

kindred epoch
#

nah

#

i think you dont know enough python for this

slate swan
#

thats what i usually do

#

long failsafes and anti bypasses

slate swan
kindred epoch
kindred epoch
hazy fulcrum
#

_ _

hollow holly
#

who can help me

#

def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)

return prefixes[str(message.guild.id)]

@client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)

prefixes[str(guild.id)] = 'py.'

with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)

prefixes.pop(str(guild.id))

with open('prefixes.json', 'w') as f:
json.dump(prefixes, f)

@client.command()
@commands.has_permision(administrator=True)
async def prefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)

prefixes[str(guild.id)] = prefix

with open('prefixes.json', 'w') as f:
json.dump(prefixes, f)
await ctx.send(f'Prefix is now {prefix}!')

#

its for server prefix in python

slate swan
#

!code

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.

rugged delta
#

does anyone know when the discord.py v2.0 is coming out ?

slate swan
#

never

hollow agate
#

Does anyone have documentations/examples on how I can add text to a stored image?

For a welcome message

slate swan
#

But using the library Pillow

#

Many examples available by searching

inner pumice
#

does anyone know how to link your bot to bloxlink

#

for a verification command etc.

#

nvm

slate swan
#

why wont this work?

#

oops images dont load

#

how to install pip on python2.7

dapper cobalt
slate swan
dapper cobalt
slate swan
#

async def kick(self, ctx , user : discord.Member):
await ctx.guild.kick(user)
if user = None:
await ctx.channel.send("You either didn't mention a user or you can't kick that user.")
else:
await ctx.channel.send(f"Successfully kicked {@<mention.user>} ")

#

Can I use user = None like that?

manic wing
#

no

dapper cobalt
#

!code for the love of god.

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.

slate swan
#

Here you go

slate swan
#

I mean, how would I fix my error.

manic wing
#

probably by learning python

slate swan
#

Thanks for the helpful answer πŸ‘

manic wing
#

there are too many mistakes for me to say them all

#

im on mobile and its hard to type

slate swan
dapper cobalt
slate swan
#

setting a default value makes more sense to me

slate swan
dapper cobalt
manic wing
#

the answer may be helpful, but not if you can’t understand it

slate swan
#

I'm reading the docs about it.

slate swan
#

error handler for commands.MissingArgument

slate swan
manic wing
#

but there are more than one errors

slate swan
dapper cobalt
slate swan
#

I'm telling u scoopy is self-promoting the hell out of this channel

dapper cobalt
manic wing
# slate swan async def kick(self, ctx , user : discord.Member): await ctx.guild.kick(...

I’m going to be a dick and be super specific to enunciate my point. For starters, ill give you the benefit of the doubt and assume that this is inside of a cog.

  • ctx.channel.send isnt needed, you can just do ctx.send
  • once the error occurs, the code will no longer run, therefore your sends are useless.
  • you can pass user=None, but dont - this means user will never equal None
  • == not =
  • you put @< inside the f-string
  • you kicked first, checked later
  • you dont need a specific error handler, just a try/except. there could be HTTPException, or many errors
slate swan
#

K thanks

dusk dust
#
@bot.command(name='captcha')
async def verify(ctx):

    number_of_strings = 1
    length_of_string = 10
    for x in range(number_of_strings):
        randomstr = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string))

    confirm = discord.Embed(
        title = 'title',
        description = 'description',
        color = 0xf1c40f
    )

    confirm.add_field(name='name_1', value='value_1', inline=False)
    confirm.add_field(name='name_2', value='value_2')

    confirm = await ctx.send(embed=confirm)
    await confirm.add_reaction('βœ…')
    await confirm.add_reaction('🚫')

i want to the bot wait for the user answer "randomstr" as a reply... how do it?

dapper cobalt
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**...
dusk dust
dapper cobalt
#

Code?

kindred epoch
#

Probably didn't even read the whole thing

dusk dust
# dapper cobalt Code?

i forget, sorry

@bot.command(name='captcha')
async def verify(ctx):

    number_of_strings = 1
    length_of_string = 10
    for x in range(number_of_strings):
        randomstr = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string))

    confirm = discord.Embed(
        title = 'title' + ctx.author.name,
        description = 'description_1 ``' + randomstr + '``. part_2 description',
        color = 0xf1c40f
    )

    confirm.add_field(name='name_1', value='value_1', inline=False)
    confirm.add_field(name='name_2', value='value_2')

    def check(message):
        return message.content == randomstr and message.channel == ctx.channel

    messag = await bot.wait_for("message", check=check)

    confirm = await ctx.send(embed=confirm)
    await confirm.add_reaction(':white_check_mark:')
    await confirm.add_reaction(':no_entry_sign:')```
i forgot, sorry
slate swan
#

Does anyone know why when i go to make a new account it says "Bots cannot access this endpoint" even tho it's me?

#

so this happened to me today, ive never had this problem before, the format i used was !Nitro

#

\:brainmon:

#

is how to get an emoji id

#

alright ty

#

inside discord

#

yeah i realized lol i thought it was server id

#

hello guys one qustion can u guys tell me how like to make my bot like invisbile i want troll my Frineds

#

wym invisible

#

like my bot is invisble mode and but my bot works

#

is that possbile?

slate swan
#

ohh

#

ya

#

.

#

i don't use them so idk

#

.

#

idk

#

so it cant possbile

#

!d discord.Status.invisible

unkempt canyonBOT
slate swan
#

so whats the code

slate swan
#

do i click on the link

#

mhm

#

everything inside the link is in the embed tho

tall canopy
#
    @commands.Cog.listener()
    async def on_member_join(self,member):
        em = discord.Embed(title=f'{member.name}',color=discord.Color.random())
        em.add_field(name='Account created',value=f"{member.created_at.strftime('%d.%m.%Y, %H:%M Uhr')}")
        em.add_field(name='Member joined',value=f"{member.joined_at.strftime('%d.%m.%Y, %H:%M Uhr')}")
        em.set_thumbnail(url=f'{member.avatar_url}')
        em.set_footer(text=f'{member.id}')
        channel = discord.utils.get(client.get_all_channels,name='xxx')
        await channel.send(embed=em)
        await member.send(f'{member.name},welcome to join our server:{member.guild.name}')

hi , why this is not function?
slate swan
#

thats what i had^

#

when i send it, Nitro is what its meant to be

dusk pumice
#

How can I get users states???

#

And What intent do I need for it.

#

Mention me for awnser please. I don't care for ping!

slate swan
#

intents = discord.Intents.all()
intents.members = True

#

just do that\

dusk pumice
#

Hmm... like ctx.user.presence?

slate swan
dusk pumice
#

Is it right

dusk pumice
slate swan
#

well then you should be fine

dusk pumice
#

Hmm

slate swan
#

are intents enabled in your bot via dev portal?

dusk pumice
#

I will try

slate swan
#

yeah you should be fine

dusk pumice
#

Okay thank you.

#

Ohh wait. It was just another errir

#

error*

slate swan
#

when i send it, Nitro is what its meant to be
![Nitro](https://cdn.discordapp.com/emojis/905207040358613002.webp?size=128 "Nitro") is whats in my source

#

\emoji

slate swan
#

but it still sent that output

#

it has to share a server with the bot

#

it does

#

is it animated?

#

nope

#

Are you sure that the bot can access the emoji?

#

its in the server

#

thats whats in the source

#

But if the bot can't see the emoji it can't sue it

#

use*

#

it can see it

#

its in the server that the emoji is from

slate swan
#

return statment

#

It can be used inside any python function either an async def or a normal python function

dusk pumice
visual island
pliant gulch
#

All the HTTP methods are under the global rate limit

#

But buckets can have different rate limits, but they also are limited by the global ratelimit

#

Funny you said that totally reminded me I should finish implementing components to my wrapper

visual island
visual island
pliant gulch
#

Coffee addict

visual island
#

haha I like tea more tho

pliant gulch
#

I'm pretty sure the gateway one does have a rate limit bucket

#

It wouldn't make sense for a rate limit on the HTTP server

visual island
visual island
pliant gulch
#

I'm just going off what the API docs says

#

It says somewhere every endpoint is under the global rate limit

pliant gulch
#

You parse there

pliant gulch
#

Uhh

#

Interaction response does have a bucket though

#

Interaction id is one of the major parameters iirc

visual island
pliant gulch
#

Wait I'm wrong I was thinking about webhook_id

#

I mean, let me just test this rq anyhow I'll read the response headers

visual island
#

okay

slate swan
#

what does [:-3] do in the cog load

pliant gulch
slate swan
#

Anyone in here who has worked with the CompontentsBot? (Buttons)

pliant gulch
#

At least that's what REMAINING: 1 is telling me (that theres 1 more left in the bucket before its depleted)

#

Oh wait no ignore what I said, I'm completely wrong lmao

#

I forgot my ratelimiter (the one which I made, and somehow forgot how it works) defaults the remaining requests left to 1 if it isn't found

#

After reading the full headers I see no X-Ratelimit- headers

visual island
#

so it doesn't have ratelimit headers?

pliant gulch
#

Yea from what I see at least

visual island
#

how about editing the response message?

#

(my last question btw)

tiny ibex
#

Can someone tell me the issue here

#

In fact it's showing so many of these erros

polar ice
#

Hey, anyone shed some light what im doing wrong? Im trying to check if the sentence containts certain words for an automatic reply

    if message.content == 'Server'.casefold() or message.content == 'IP'.casefold():
        msg = "The IP address is XXXXX"
        await message.channel.send(msg)
pliant gulch
#

Yes edits have a ratelimit

#

It seems like 5/5s

blazing coral
#

@client.command()
@commands.has_permissions(administrator=True)
async def strike(ctx, member: discord.Member, *, reason):

current_strike_count = len(
        await bot.strike.find_many_by_custom(
            {
                "user_id": member.id,
                "guild_id": member.guild.id
            }
        )
    ) + 1

strike_filter = {"user_id": member.id, "guild_id": member.guild.id}
strike_data = {"reason": reason, "timestamp": ctx.message.created_at, "strike_by": ctx.author.id}
await bot.strike.upsert_custom(strike_filter, strike_data)
embed = discord.Embed(
    title="you have been given a strike:",
    description=f"__**Reason**__:\n{reason}",
    colour=discord.Colour.red(),
    timestamp=ctx.message.created_at)
embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)
embed.add_feild(name=f"strikes:, value={current_strike_count}", incline=True)

await ctx.send(embed=embed)
#

no errors given just wont send anything to the discord

#

if someone can she some light on this that would be great

visual island
pliant gulch
#

Yea I used the token to get the endpoint

#

I mean, I'm pretty sure you have to use the token to get the correct endpoint

visual island
#

i see thanks

warm bane
#

I'm a beginner with Python and been watching videos/exploring the documentation for discord.py. I started using Cogs, but can't figure out what I'm missing to get this dropdown list to display. I think it might be related to the ComponentsBot part, but unsure how that would impact the other code and where I need to designate it. Here is the code for the cog:

from discord.ext import commands
from discord_components import Button, Select, SelectOption, ComponentsBot

class Menu(commands.Cog): # Category type is the class
def init(self, bot): # using self bc using class
self.bot = bot

@commands.command(brief="Provides a menu of all Bot commands")
async def menu(self, ctx):

await ctx.send(content = 'Select an option:', components=[Select( 
                                              placeholder='Please select an option.',
                                              Options = [
                                                SelectOption(label='Option 1', value='1'),
                                                SelectOption(label='Option 2', value='2'),
                                                SelectOption(label='Option 3', value='3'),
                                                SelectOption(label='Cancel', value='Cancel'),
                                              ],
                                              custom_id='MainMenu'
)])
interaction = await self.bot.wait_for('select_option', check=lambda inter: inter.custom_id == 'MainMenu' and inter.user == ctx.author)
res=interaction.values[0]

if res == 'Cancel':
  await interaction.send('You have canceled your select option')
else:
  await interaction.send('You have selected %s option' % (res.label))

def setup(bot):
bot.add_cog(Menu(bot))

sick birch
boreal ravine
#

cringe third party libs

warm bane
#

yeah, it's been a struggle

sick birch
warm bane
#

slow progress, def have had to hunker down and learn the core of what they arent teaching

sick birch
#

discord.py natively have support for buttons and select menus

boreal ravine
sick birch
#

why the 3rd party libs?

warm bane
#

i eventually want this to be dynamic, but i need to build the skill for it

sick birch
sick birch
warm bane
#

open to advice

sick birch
#

there are plenty of really good examples in the discord.py examples/view/ subfolder

#

(i wrote one myself :))

boreal ravine
#

really

warm bane
#

the documentation is alright, but not always easy to find what im looking for

sick birch
warm bane
#

ok

#

awesome, ill take a look

boreal ravine
blazing coral
#

yo robin could you look at somthing for me pls

sick birch
#

great, best of luck, if you need any more help feel free to come back!

warm bane
#

do you have it setup for cogs or is there a better way to do this without it all being one file?

sick birch
#

extensions

#

you can have cogs in different files and load it that way

warm bane
#

from keep_alive import keep_alive
from discord_components import Button, Select, SelectOption, ComponentsBot

import os
from discord.ext import commands
from settings import *

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!!'))

for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "init.py":
bot.load_extension(f'cogs.{filename[:-3]}')

@bot.event
async def on_ready():
print(f'Logged in as {bot.user}.')

keep_alive()
bot.run(os.getenv('TOKEN'))

sick birch
#

can you code block that please

#

```py
CODE HERE
```

warm bane
#

'''py
from keep_alive import keep_alive
from discord_components import Button, Select, SelectOption, ComponentsBot

import os
from discord.ext import commands
from settings import *

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!!'))

for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "init.py":
bot.load_extension(f'cogs.{filename[:-3]}')

@bot.event
async def on_ready():
print(f'Logged in as {bot.user}.')

keep_alive()
bot.run(os.getenv('TOKEN'))
'''

sick birch
#

backticks, not quotations

warm bane
#

hmm, not sure im tracking you

boreal ravine
warm bane
#

oh

boreal ravine
#

!code

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.

sick birch
#

it's the key beneath the esc key

boreal ravine
#

just edit the message

#

no need to send it again

sick birch
warm bane
#
from keep_alive import keep_alive
from discord_components import Button, Select, SelectOption, ComponentsBot

import os
from discord.ext import commands
from settings import *

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!!'))

for filename in os.listdir("./cogs"):
    if filename.endswith(".py") and filename != "__init__.py":
        bot.load_extension(f'cogs.{filename[:-3]}')

@bot.event
async def on_ready():
  print(f'Logged in as {bot.user}.')

keep_alive()
bot.run(os.getenv('TOKEN'))
sick birch
#

thanks

warm bane
#

much better

blazing coral
#
@commands.has_permissions(administrator=True)
async def strike(ctx, member: discord.Member, *, reason):

    current_strike_count = len(
            await bot.strike.find_many_by_custom(
                {
                    "user_id": member.id,
                    "guild_id": member.guild.id
                }
            )
        ) + 1

    strike_filter = {"user_id": member.id, "guild_id": member.guild.id}
    strike_data = {"reason": reason, "timestamp": ctx.message.created_at, "strike_by": ctx.author.id}
    await bot.strike.upsert_custom(strike_filter, strike_data)
    embed = discord.Embed(
        title="you have been given a strike:",
        description=f"Reason:\n{reason}",
        colour=discord.Colour.red(),
        timestamp=ctx.message.created_at)
    embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)
    embed.add_feild(name=f"strikes:, value={current_strike_count}", incline=True)

    await ctx.send(embed=embed)```
boreal ravine
#

@blazing coral error?

sick birch
#

but again, i would suggest use discord.py's native UI kit, rather than discord_components

blazing coral
#

it dosnt give an error thats the thing

sick birch
#

do you have an error handler?

blazing coral
#

it just wont work

blazing coral
boreal ravine
sick birch
warm bane
#

i'll check your code out and be back

#

its getting late here so might need to bug you again tomorrow or later this week

#

thanks again

sick birch
#

it's alright, plenty of others here to assist!

blazing coral
#

what do you mean by this

sick birch
#

your error handler might be eating up the errors

#

just comment it out for now

blazing coral
#

so like

boreal ravine
#

eating up all the errors*

sick birch
#

yeah that

blazing coral
#

this thing

boreal ravine
#

yes

sick birch
#

mmhm

boreal ravine
#

!code pls

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.

blazing coral
#

yeah hold up forgot to do that

boreal ravine
#

dont send it again

blazing coral
#
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        embed = discord.Embed(
            title='Command Error ',
            description=' somthing went wrong ',
            colour=discord.Colour.red())

        embed.add_field(name=" Missing Reqired Arguments ", value=" Please pas in all requirements for command to work",
                        inline=True)
        await ctx.send(embed=embed)```
boreal ravine
#

just comment it out

sick birch
#

i.e it doesn't pass the if statement?

boreal ravine
#

just add an else statement

#

and raise the error

sick birch
blazing coral
#

all that dose is tell me like if i didnt type the command in correctly

sick birch
blazing coral
#

im pretty sure here let me get a pic for you

sick birch
#

your code basically says "oh, this error is not commands.MissingRequiredArgument, i'll just ignore it and move on"

#

which is not what we want whilst troubleshooting

boreal ravine
#

just add an else statement and raise the error there

sick birch
#

ah yeah reraising

boreal ravine
#

or do what robin said

blazing coral
#

all the error handler dose that is if thats what your talking about

blazing coral
#

ok never done an else statement how about would i start that its somthing new

boreal ravine
#

learn more python?

sick birch
#

it ignores all other errors completely

#

which you should never do

#

errors are extremely important

blazing coral
#

so get rid of it

#

and see what happens

sick birch
#

you could

#

or comment it out

#

or reraise the error

#

or use the traceback library

#

plenty of options, you choose

blazing coral
#

i got rid of it

sick birch
#

okay, try running it now and see what happens

blazing coral
#

nothing has come up

#

let me try the command

blazing coral
sick birch
#

that's progress

#

some error is better than no error

slate swan
#

bruh why are they stacked like that

#

it's DiscordComponents idk if that relates to this channel in any way

sick birch
#

ah then i'm not sure, i don't like the 3rd party libraries they're kinda bad imo

blazing coral
#

its a no attribute error for the word strike

#

which im confused why

sick birch
#

can you post the full traceback?

blazing coral
#

i tried somthing to see if that worked

elfin moon
#

i am trying to run my discored bot but i am getting this error -> aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)]

thick rampart
#

Hey how do you get a bot to assign roles based on user inputs?
like if you see five words and you use one of the five words to describe yourself it should assign a role
or am I smoking crack?

elfin moon
#

yeah

sick birch
#

you might be connecting to HTTP instead of HTTPS

slate swan
#

hey i need help py AttributeError: module 'discord' has no attribute 'Intents'

blazing coral
# sick birch can you post the full traceback?

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\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: module 'discord.ext.commands.bot' has no attribute 'strike'

sick birch
#

yeah the error speaks for itself

#

bot.strike is invalid

#

is bot.strike supposed to be a class?

elfin moon
#
bot = commands.Bot(command_prefix='+')
bot.remove_command('help')
client = discord.Client()

# more code but i wont show it because it doesnt matter

bot.run(os.environ['DISCORD_TOKEN'])
client.run(os.environ['DISCORD_TOKEN'])
sick birch
#

why are you running both a client and a bot?

elfin moon
#

also i imported discord and stuff

slate swan
#

Check a member’s voice channel ID (if they are in a voice channel tell me the ID) {ping me}

elfin moon
#

i am using client to change the profile picture

sick birch
sick birch
#

there is absolutely no need to be using both

elfin moon
#

oh

thick rampart
elfin moon
#

wait

thick rampart
#

yeah, is that pulling from the discord import?

sick birch
#

not necessarily, it's a decorator

#

if you mean the @bot.command() on top of every function

elfin moon
#
bot = commands.Bot(command_prefix='+')
bot.remove_command('help')

# more code but i wont show it because it doesnt matter

bot.run(os.environ['DISCORD_TOKEN'])
#

but it still doesn't work

sick birch
slate swan
thick rampart
#

from discord.ext import commands like what commands does this import?

sick birch
elfin moon
#
import traceback
import discord, random, asyncio, pickle, os, sys, inspect, datetime, glob
from discord.ext import commands, tasks
from collections import OrderedDict
import copy
slate swan
sick birch
elfin moon
#

i am using other imports for other stuff

sick birch
slate swan
#

Thanks

thick rampart
#

I did not know there was a task extension

elfin moon
#

discord.Intents?

#

or just Intents

sick birch
#

discord.Intents in your case

elfin moon
#

what does it do?

#

the import is not used

sick birch
#

well you need intents right?

#

if you're doing discord.Intents, you don't have to import intents seperately

#

it's preferable as you don't flood your namespace

elfin moon
#

ModuleNotFoundError: No module named 'discord.Intents'

sick birch
#

are you doing

import discord.Intents
```?
waxen torrent
warm bane
warm bane
#

thanks

sick birch
#

probably why

#

you don't need that import

elfin moon
#

you just said to import it

sick birch
#

all you need is

import discord

then you can do

intents = discord.Intents()
elfin moon
#

ya but why do i need intents

sick birch
#

you really don't

#

it just reduces computational strain

elfin moon
#

ok

#

what does that line of code do?

#

intents is not used in the program just declared.

slate swan
#
    @commands.command()
    async def move(self, member):
        # first_channel = (897862720538419231)
        main_channel = member.voice.channel
        second_channel = self.client.get_channel(897862929142128650)
        member.move_to(second_channel)
        member.move_to(main_channel)
#

why this doesn't work?

#

Please ping me!

sick birch
#

pretty sure move_to needs you to await it

#
  • you're moving them to and back instantaneously
elfin moon
#

nope still same error aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)]

sick birch
#

can you send the full traceback + code?

elfin moon
#

yeah

unkempt canyonBOT
elfin moon
slate swan
sick birch
elfin moon
#

how do i know that

sick birch
#

get rid of the env variables temporarily, and put the token in as plaintext for testing purposes

elfin moon
#

ok

#

still error

#

😦

sick birch
#

token is in string format?

elfin moon
#

yes

sick birch
#

it's copy pasted from the discord dev portal?

elfin moon
#

bot.run('aweytaweaeauvbwgeytacmerauceiracne')

#

yeah

sick birch
#

i see

elfin moon
#

i just regenerated

#

and pasted it

sick birch
#

did you put the new one in?

#

oh

elfin moon
#

yes

sick birch
#

that's super odd

elfin moon
#

yeah

#

it says wrong version number

sick birch
#

that's super odd

elfin moon
#

eys

#

perhaps i should ressstart my computer

sick birch
#

maybe

slate swan
#

mr robin

#

@sick birch help

sick birch
#

yeah?

#

can i... help you?

elfin moon
#

hi

#

still not working

#

it's so sad

slate swan
#

umm

#

@sick birch sorry for lag!

#

actually i wanna know prefix of my server wit hmy bot commands with discord .py

slate swan
#

ohhh!

#

how ctx?

#

ctx define ctx please likt ctx:

#

i am using on message

#

ok 1 sec

sick birch
#

ah

#

i sense something funky going on

#

why do you need the prefix in on_message?

slate swan
elfin moon
#

yes

slate swan
spiral frigate
#

how to pass the argument that the user wrote to error handler

slate swan
slate swan
#

what?

spiral frigate
slate swan
#

i dmed him

spiral frigate
sick birch
#

oauth is only for autentication

#

you can GET /user/@me/guilds (iirc) to get a guilds

#

authenticate with the access token

sick birch
#

/users/@me/guilds gets all the guilds afaik

spiral frigate
sick birch
#
raise someError("some message I want to raise")
slate swan
spiral frigate
slate swan
#

Call it with bot and message as args

spiral frigate
sick birch
#

well, the raised error gets propagated to the error handler yes?

#

that is what you wanted?

spiral frigate
#

I want to pass the argument of the commandmember:discord.Member = None in the error handler

sick birch
#

like, "Invalid user"?

spiral frigate
#

well, the person writes:
command arg
I need 1arg

sick birch
#

well that won't raise any errors

spiral frigate
#

no, like I have an error handler that handles 'membernotfound` and I need it to write 1 argument

sick birch
#

so, if the member says invalid user like

#

command @someuser

#

and if they don't exist, the error handler says "someuser" doesn't exist?

spiral frigate
#

yes

#

well, do you know or not

#

???

#

Well

#

@sick birch

manic wing
slate swan
#

how do i make my bot delete the message it responded to like

if "Hello" in response.content:

so for example my bot responds "world" and i want it to delete the "hello" that the person sent

urban shell
#

hey guys, can someone help me out, wtv method I try to get the member's info, it always returns None, I've tried guild.get_member(id) as well

   
   if ">vcpermit" in message.content and message.author.id in self.mv:
            guild = message.guild
            c = str(message.content)
            d = c.replace(">vcpermit <@!", "")
            g = d.replace(">", "")
            h = int(g)
            m = discord.utils.get(guild.members, id=h)
            e = self.mv.index(message.author.id)
            f = self.vi[e]
            vn = discord.utils.get(guild.channels, id=f)
            print(m)
            await vn.set_permissions(m, connect=True)
            s = "<@" + g + "> has been permitted to your VC!"
            await message.channel.send(s)
slate swan
#

i want the message my bot responded to be deleted.
Me:Hello (Wants to be auto deleted)
Bot Responds: World

slate swan
#

1min

#
if "It's " in response.content:
            break
        intervals = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
        sleep(random.choice(intervals))
      s = response.content.split(" is ")[1].replace(".","")
      #response.delete()
      print(s)
      x = get_mon(s)
      #print(options)
      print(x)
      first_options = x
      for i in first_options:
        await message.channel.send("It's "+i)
#

@urban shell

urban shell
#

the message that the bot sent?

slate swan
#

no the message it responded to

urban shell
#

hmm

urban shell
slate swan
#

yes ty

#

help\

#

help

#

help

#

!mute 785710193517396008 5d You still haven't improved your behaviour. Unless you can be patient, please don't request help here.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1636355431:f> (4 days and 23 hours).

simple jolt
#

hey I wanted to ask if anyone wanted to collab make some bots with python if so Dm me

slate swan
#

This is not really the right place to find developers, there are websites made for that

final shard
#

Add emoji function?

#

To add emojis using bot

slate swan
#

Reaction?

#

!d discord.Message.add_reaction

unkempt canyonBOT
#

await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
jade tartan
#

Hi so am trying to make a discord button and so when i click on the button in my server it says This interaction failed

#
async def button(ctx):
    await ctx.message.delete()
    await ctx.send(
        "This is a button",
        components = [
            Button(label = 'Click Me!')        
        
        ]
    )
    interaction = await client.wait_for("button_click", check=lambda i:  i.component.label.startswith("Clicks"))
    await interaction.respond(content="Button Clicked")
#

that's my code

slate swan
#

Hi all! please tell me how to use the command on two people, like here:

#

@lusty swallow

final shard
slate swan
#

!d discord.Guild.create_custom_emoji

unkempt canyonBOT
#

await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji") for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
final shard
#

oh

jade tartan
#

Ain’t no body gonna answer me?

final shard
#

thx

final shard
jade tartan
#

Hi so am trying to make a discord button and so when i click on the button in my server it says This interaction failed

#
async def button(ctx):
    await ctx.message.delete()
    await ctx.send(
        "This is a button",
        components = [
            Button(label = 'Click Me!')        
        
        ]
    )
    interaction = await client.wait_for("button_click", check=lambda i:  i.component.label.startswith("Clicks"))
    await interaction.respond(content="Button Clicked")
slate swan
#

Your button label doesn't even start with Clicks

#

So the check will never work

maiden fable
#

Yes

tough lance
#

Yes

final shard
#

How to make a error command with raises like "Forbidden" and HTTPexception"

#

Just an example

maiden fable
final shard
#

the dots

maiden fable
#

!d discord.Forbidden

unkempt canyonBOT
#

exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.

Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/master/api.html#discord.HTTPException "discord.HTTPException")
maiden fable
#

see the args it accepts

#

!d discord.HTTPException

unkempt canyonBOT
#

exception discord.HTTPException(response, message)```
Exception that’s raised when an HTTP request operation fails.
final shard
#

okie

slate swan
#

Then use the awesome search function

#

And you see this

#

Well if you don't give an authorization header you won't go far

#

Try it and see

#

Reading the Discord's API documentation is helpful

#

Everything is explained perfectly...

boreal ravine
#

Does anyone know what discord's api link for DMs is

slate swan
#

Just like any normal channel

#

Saying "Didn't work" doesn't help to understand what doesn't work...

#

No need to send it again you know right?

boreal ravine
boreal ravine
slate swan
#

Well what did you tried to do

boreal ravine
#

requests.post("the url", json=data, headers=header)

slate swan
#

What are you trying to do and what is the url

boreal ravine
#

post something in a dm channel

slate swan
#

something, a message right?

boreal ravine
#

yes

slate swan
#

What is the URL

boreal ravine
#

https://discord.com/api/v9/channels/646303683759439877

slate swan
#

Yeah, the docs will help you

boreal ravine
#

well i did say it was a dm channel

slate swan
#

Doesn't matter

#

You need to add /messages at the end to send (post) a new message...

boreal ravine
#

o

slate swan
boreal ravine
#

its saying b'{"message": "Unknown Channel", "code": 10003}' now

tall canopy
#

hello.Why my bot doesnt online after deployed?

boreal ravine
#

is access_token and guild_id defined

#

when calling the function

slow forum
#

Can i find there any devs for discord bot?

boreal ravine
#

maybe

ornate lichen
#

hi

#

need some help

unkempt canyonBOT
ornate lichen
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 112, in on_message
    async for submission in top:
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/models/listing/generator.py", line 63, in __anext__
    await self._next_batch()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/models/listing/generator.py", line 73, in _next_batch
    self._listing = await self._reddit.get(self.url, params=self.params)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/reddit.py", line 627, in get
    return await self._objectify_request(method="GET", params=params, path=path)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/reddit.py", line 731, in _objectify_request
    await self.request(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/reddit.py", line 930, in request
    return await self._core.request(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 370, in request
    return await self._request_with_retries(```
#
 File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 270, in _request_with_retries
    response, saved_exception = await self._make_request(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 187, in _make_request
    response = await self._rate_limiter.call(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/rate_limit.py", line 34, in call
    kwargs["headers"] = await set_header_callback()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 322, in _set_header_callback
    await self._authorizer.refresh()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/auth.py", line 423, in refresh
    await self._request_token(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/auth.py", line 153, in _request_token
    response = await self._authenticator._post(url, **data)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/auth.py", line 41, in _post
    raise ResponseException(response)
asyncprawcore.exceptions.ResponseException: received 401 HTTP response```
#

im getting this error

boreal ravine
#

Whats the error

#

ah

#

you need to authorize it using something

slate swan
spiral frigate
#

how to pass the argument that the user wrote to error handler

boreal ravine
spiral frigate
#

so, if the member says invalid user like
command @someuser
and if they don't exist, the error handler says "some user" doesn't exist

boreal ravine
#

maybe idk

spiral frigate
boreal ravine
#

yes

slate swan
#

Pycord da best!!!

slate swan
#

In nextcord it changes from discord to nextcord that's why I don't like that

tall canopy
tough lance
boreal ravine
#

well yes

spiral frigate
#

please help me for 3 hours I can't decide

slate swan
#

Btw you use nextcord?

spiral frigate
#

-_-

slate swan
#

Without code we can't help Β―_(ツ)_/Β―

ornate lichen
#

ok ill send it

boreal ravine
#

does ur bot have guilds scope

ornate lichen
#
import asyncpraw
reddit = asyncpraw.Reddit(
  client_id=os.getenv("CI"),
  client_secret=os.getenv("CS"),
  user_agent="lol23",
  username="awaffle11",
  password=os.getenv("P")
)

@client.event
async def on_message(message):
  if message.author==client.user:
    return

elif message.content.startswith(">meme"):
   subreddit = await reddit.subreddit("memes")
   all_subs=[]
   top = subreddit.top(limit = 100)
   
   async for submission in top:
    all_subs.append(submission)
  
   random_sub =random.choice(all_subs)
   name=random_sub.title
   url=random_sub.url
   em= discord.Embed(title=name)
   em.set_image(url=url)
   await message.channel.send(embed=em)
#

this is the code

boreal ravine
ornate lichen
#

yup i am

#

im using reddit to import memes

#

and i checked all my particualrs

final shard
#

how to detect a reaction click

heavy folio
#

if i wanna import something from my file do i do from utils/utils.py import something? idk how
my directory for the file is \main\utils\utils.py
where main.py is in \main

boreal ravine
#

you also cant have .py in your imports

heavy folio
#

if its in a folder

boreal ravine
#

you can import it using from folder.file import object

#

folder is your folder name and file is the file name inside the folder

gaunt herald
#

I need to make kick and ban command, but if someone have role i cant kick him. How can I fix this?

boreal ravine
#

what role

gaunt herald
#

Any role

#

@boreal ravine

slate swan
#

put the bot to a higher hierarchy

#

than the roles

loud goblet
#

Hello

#

I made a discord bot and now I want to make a dashboard for it

pastel cobalt
#

hi

loud goblet
#

So how can I do it

pastel cobalt
#

i guess we have to develop a website of our own

slate swan
#

Using Flask

loud goblet
#

The info I want to show is the number of servers it's invited and the number of people

loud goblet
slate swan
#

Enough tutorials on the Internet

#

Do your own research

pastel cobalt
# slate swan Enough tutorials on the Internet

i used task.loop function to check my databse and says whether anyone had birthday today.
But when i task.loop function some other commands are not working.
Can someone help me how to fix this?\

slate swan
#

your database is probably blocking

#

What db do you use?

pastel cobalt
slate swan
#

Pymongo or motor?

pastel cobalt
slate swan
#

you should use motor in asynchronous code

#

!PyPi motor

unkempt canyonBOT
pastel cobalt
crystal kestrel
#

how can I get the amount of messages that are being sent every second? my current code:

def messages_per_second():
    differences = []
    counter = 0
    current_time = 0
    for cached_message in client.cached_messages:
        sent_time = cached_message.created_at.timestamp()
        if sent_time - current_time > 1:
            differences.append(counter)
            current_time = sent_time
            counter = 0
        else:
            counter += 1
    average = round(sum(differences)/len(differences), 2)
    return average

i dont feel like this is correct tho

spiral frigate
#

how to make a message that only the one who called the command sees

crystal kestrel
#

u cant unless u use interactions

spiral frigate
#

it's like

spiral frigate
#

?

crystal kestrel
#

slash commands

spiral frigate
#

and they are in py-cord

crystal kestrel
#

im not sure if interactions are supported in discord.py but in disnake its ```py
@client.slash_command(name="ping", description="Pong")
async def ping_command(interaction):
await interaction.response.send_message("Pong", ephemeral=True)

spiral frigate
#

disnake is better than py-cord?

crystal kestrel
#

idk

#

i prefer it personally

spiral frigate
#

and will you be able to throw off the option for cog

crystal kestrel
#

?

maiden fable
boreal ravine
boreal ravine
spiral frigate
tough lance
#

I prefer disnake

final shard
#

How to detect a reaction on a message

boreal ravine
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
final shard
#

what should i do

#

I want a message to be send when a reaction is detected on a message

boreal ravine
final shard
#

oh hmm i thought that was for adding reaction

spiral frigate
#

how to get a command message

tough lance
#

For reaction removal,

#

!d discord.on_reaction_remove

unkempt canyonBOT
#

discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.

Note

To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.

Note

Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
stray mural
#

so im making a bot with Component with the discord_components libirary
My problem is that the Componentctx object returns None when asking for message attribute although in the docs it says that there is a message attribute for Componentctx type

jade tartan
slate swan
#

Well, think a little bit. If you have a string that is Click me and you check if the string starts with Clicks, do you think it will find it?

jade tartan
#

Because yeah maybe videos dont really look the same as you do it in your own code if that make sense

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

jade tartan
#

Ok

#

I got a question

#

Can python bots create a staff application where ppl would answer a bunch/some questions and then the answers would get send to you for review

#

And then it sends a dm to either that u got accepted or denied and for whatever results it states your reason

rain olive
#

yes.

#

using the wait_for methods

slate swan
#
import discord
from discord.ext import commands
import time

# -------------------- Cogs --------------------

class movespam(commands.Cog):
    def __init__(self, client):
        self.client = client

# -------------------- Launch --------------------

    @commands.Cog.listener()
    async def on_ready(self):
        print('Loaded Move Spam')

    def is_it_me(ctx):
        return ctx.author.id == 850727380220772415
        
# -------------------- Spam Moves --------------------

    @commands.command()
    @commands.check(is_it_me)
    async def move(self, member):
        main_channel = self.client.get_channel(879332800656986152)
        second_channel = self.client.get_channel(897862929142128650)
        await member.move_to(second_channel)
        time.sleep(1)
        await member.move_to(main_channel)
                
# -------------------- Cogs Setup --------------------

def setup(client):
    client.add_cog(movespam(client))

# -------------------- Comment --------------------

Why this isn't working? I get no errors

jade tartan
rain olive
#
@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that thumbsup reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == 'thumbsup'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('thumbsdown')
        else:
            await channel.send('thumbsup')
#

here's an example

slate swan
#

And if you want to spam move the user, you might want to make a loop

kindred epoch
#

Idek what he's trying to do

slate swan
kindred epoch
#

Member is just a str

#

You need an actual member object

slate swan
#

member : discord.Member?

kindred epoch
#

Ye

slate swan
# kindred epoch Ye
import discord
from discord.ext import commands
import time

# -------------------- Cogs --------------------

class movespam(commands.Cog):
    def __init__(self, client):
        self.client = client

# -------------------- Launch --------------------

    @commands.Cog.listener()
    async def on_ready(self):
        print('Loaded Move Spam')

    def is_it_me(ctx):
        return ctx.author.id == 850727380220772415

# -------------------- Spam Moves --------------------

    @commands.command()
    @commands.check(is_it_me)
    async def move(self, member : discord.Member):
        main_channel = self.client.get_channel(879332800656986152)
        second_channel = self.client.get_channel(897862929142128650)
        await member.move_to(second_channel)
        time.sleep(1)
        await member.move_to(main_channel)
                
# -------------------- Cogs Setup --------------------

def setup(client):
    client.add_cog(movespam(client))

# -------------------- Comment --------------------
#

Still doesn't work man

#

error?

spiral frigate
#

how to use 'inter.response` in error handler

slate swan
slate swan
#

also , dont use time.sleep in async code

#
import asyncio

await asyncio.sleep(time)``` use this
jade tartan
#

using the wait_for methods are you talking about?

slate swan
#

you only have ctx in an error handler

dusk dust
#
@bot.command(name='captcha')
async def verify(ctx):

    number_of_strings = 1
    length_of_string = 10
    for x in range(number_of_strings):
        randomstr = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string))

    confirm = discord.Embed(
        title = 'title ' + ctx.author.name,
        description = 'part_1: ``' + randomstr + '``. part_2',
        color = 0xf1c40f
    )

    confirm.add_field(name='name_1', value='value_1', inline=False)
    confirm.add_field(name='name_2', value='value_2')

    member = ctx.author
    confirm = await ctx.send(embed=confirm)

    def check(message, user):
        return user == ctx.message.author and message.channel == ctx.message.channel and user != user.bot

    await bot.wait_for("message", check=check)
    await bot.add_roles(member, role)

I want to the bot get the answer (in case, the randomstr) and then check if this answer is correct but my code are wrong and i don't know what

slate swan
#

use try and except wherever you use the button responses

#

except lmao

#

autocorrect , something likely to happen on an android device

slate swan
#

mhm

#

It print's the on ready thing

slate swan
slate swan
#

show your current code

slate swan
#

Thank you so much

#

np

simple jolt
#

AttributeError: type object '_asyncio.Task' has no attribute 'current_task'

#

what is this error?

#

issue with this import from discord.ext import tasks

#

the whole code works fine on repl it but not on my local pc

boreal ravine
#

hm

#

outdated modules maybe

simple jolt
#

ohh nvm I was using python 3.9

boreal ravine
#

o

simple jolt
#

thanks for the help

boreal ravine
#

πŸ‘

simple jolt
boreal ravine
#

not sure

simple jolt
#

hmm

maiden fable
stray mural
#

so im making a bot with Component with the discord_components libirary
My problem is that the Componentctx object returns None when asking for message attribute although in the docs it says that there is a message attribute for Componentctx type

boreal ravine
unkempt canyonBOT
boreal ravine
#

use that to check if its a certain command

#

Why not just use the humanize module instead of doing math?

#

!pypi humanize

unkempt canyonBOT
boreal ravine
#

^ Converts literally anything into seconds, minutes, hours, days, weeks or even years

boreal ravine
#

well

#

you only called the function

#

u didnt add any arguments

rotund nova
#

what bad here?

#
@client.event
async def on_member_remove(member):
    channel = client.get_channel(902965184044335155)
    embed=discord.Embed(title=f"Ε»egnaj {member.name}...", description=f"Ε»egnaj, mamy nadzieje ΕΌe kiedyΕ› wrΓ³cisz jeszcze na nasz serwer!", colour=discord.Colour.red)
    embed.set_thumbnail(url=member.avatar_url)
    await channel.send(embed=embed)
boreal ravine
#

and not discord.Color.red

final shard
#

what is the official way for making buttons

rotund nova
slate swan
rotund nova
#

ok

slate swan
boreal ravine
slate swan
#

Yes

final shard
slate swan
#

Oof

final shard
slate swan
#

Use pycord instead

final shard
boreal ravine
final shard
boreal ravine
#

just add () after.red
add

#

did you read the message

slate swan
#

Always first delete discord.py then install whatever lib you want

final shard
#

or error

boreal ravine
final shard
#

...nvm i cant explain its my fault

boreal ravine
#

ok

final shard
slate swan
#

Np

#

Always there for help, i love helping

rotund nova
#
    activity = discord.Game(name="McForever.eu - Najlepszy serwer minecraft.", type=2)
    await client.change_presence(status=discord.Status.idle, activity=activity)
``` can i change it to status online?
rotund nova
slate swan
#

What is the error??

rotund nova
#

dont error i just want online but idk how

slate swan
#

Ohh

rotund nova
#

bot have that

#

moon

slate swan
#

Lol just change the type=1

rotund nova
#

ok

slate swan
#

Try that

rotund nova
#

thx

slate swan
#

Or else it could be 0 i am not sure

#

Cuz i use different statement for status

#

@rotund nova it worked?

#

Please just let the helper always know @rotund nova whenver you ask ok?

#

If it works or not

sage otter
slate swan
#

Lol exactly

sage otter
sage otter
#

It will default the status to online

fallen mica
#

Quick question, which data base would be the best to start of with for bots?

sage otter
#

Sqlite if you’re not planning on going big

#

Postgres if you are

fallen mica
#

Alright, thanks.

slate swan
slate swan
#

Ok

#

UwU

rotund nova
slate swan
#

No

sage otter
#

No

slate swan
#

Lol

sage otter
#

I said status

spiral frigate
#

how to make a command that will give a link to a video on YouTube

slate swan
#

Wait yes

rotund nova
#
    await client.change_presence(activity=activity)
slate swan
#

So do online

rotund nova
#

?

slate swan
#

Yes

sage otter
#

bro I literally said delete it because it will default onto online. Why pass in unnecessary arguments

slate swan
#

Wait bettrr i will trll @rotund nova a better method

boreal ravine
fallen mica
slate swan
#
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.Game, name="your status"```
spiral frigate
sage otter
slate swan
#

@rotund nova

rotund nova
#
@client.command(name='link')
async def youtube(ctx):
    print(ctx.author.name)

    await ctx.send("link")
```?
boreal ravine
#

hm

untold token
#

Do not change status in an on_ready event

#

use the bot constructor itself to do that

sage otter
#

Link would undefined unless it’s in some outer scope

loud goblet
#

Hello. If I make a dashboard for my bot will people be able to see it on Google

#

The invite link

sage otter
#

And you’re missing a terminating double quote

sage otter
ivory sluice
#

Hi guys. I am getting this error in this line

try:
    reaction , user = await client.wait_for("reaction_add", check = lambda reaction,user: user == ctx.author and   
    reaction.emoji in buttons and reaction.message.id == msg.id, timeout = 40)

Error:

AttributeError: module 'discord.client' has no attribute 'wait_for'

It was working fine in 'main.py' but started to give this error when I re-wrote it in a cog.

gaunt herald
#

Hey i need free host my bot. How can i do it?

sage otter
#

there’s multiple ways

ivory sluice
sage otter
#

don’t use repl.it. That’s terrible

gaunt herald
gaunt herald
#

Some code are not working

ivory sluice
sage otter
#

What’s used often are vps's(or dedis), rasp pi, some people use old laptops as well

ivory sluice
sage otter
# ivory sluice I host mine in heroku. Its fine. no problems, not that great either.

- Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.

- Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.

- Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.

- Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)

- Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
sage otter
ivory sluice
sage otter
#

What about in your cog

ivory sluice
#

main_folder

  • cogs
    | ---help.py
    -main.py
#

its structured like this

sage otter
#

Oh, is that snippet of code you have in your main?

ivory sluice
#

yes

slim whale
#

do i need to import discord-interactions for slash commands=?

sage otter
ivory sluice
#

exactly

#

also where can I report people from this server.

sage otter
#

The modmail

slate swan
#

check your imports

#

hello

@client.command()
@commands.has_permission(administrator=true)
async def hello world(ctx):
await ctx.send(f"hello {ctx.author.mention})

this is not works