#discord-bots

1 messages · Page 582 of 1

unkempt canyonBOT
elfin island
#

I think get_channel should work fine? Will probably return a CategoryChannel

slate swan
#

Hm

boreal ravine
#

yes

tidal hawk
#

thanks

slate swan
#

Wait what , discord.Bot?

boreal ravine
#

oops my bad

slate swan
#

discord.Client is

boreal ravine
#

wrong library

slate swan
#

yeah that's for pycord iirc

elder meteor
#

i need a code on how my bot gives someone a role whenever someone joins my server

boreal ravine
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

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, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate swan
#

How would I get the message that was interacted from in the “on_button_click” event

slate swan
quick spear
#

whether the type of target in classification shouldn't have boolean?

slate swan
#

?

#

Wdym by "classification"

elder meteor
#

!d discord roles

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

slate swan
#

??

elder meteor
#

grrrr

slate swan
#

For self-serving commands in #bot-commands

boreal ravine
unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
elder meteor
boreal ravine
#

Ok

boreal ravine
slate swan
#

Perhaps

waxen granite
#

U can use discord.utils.get too

boreal ravine
waxen granite
#

What

slate swan
#

If you have the ID never ever even consider using utils.get

boreal ravine
#

I think discord.utils.get() is only useful if your looking for a channel that has the same name

slate swan
#

^

waxen granite
#

Well it works too , w/e

boreal ravine
#

yes

slate swan
#

utils.get basically iterates over whatever array you give it, and checks if the name is equal with the one you gave

slate swan
boreal ravine
#

discord.utils.get() is just a fancy name for a for loop xD

waxen granite
#

Well good in times of multiple guilds

shadow wraith
#

whenever i try to run my bot it alwasy appears with this error
Exception has occurred: ClientConnectorCertificateError
Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]

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

File "/Users/sadancooler/Documents/Code/Python/discord-bots/beginner.py", line 14, in <module>

#

line 14 is client.run('token') btw

slate swan
#

Assuming the channel that we're looking for is discord-bots and that the array we give, is ctx.guild.channels, the only thing utils.get does is this ```py
for channel in ctx.guild.channel:
if channel.name == 'discord-bots':
return channel

shadow wraith
#

im new to making discord bots through python but this crap annoys me

slate swan
shadow wraith
boreal ravine
#

hm

shadow wraith
#

i just run and debugged through visual studio code

#

i can assure its not a vsc display issue because the bot actually doesn't turn online

slate swan
waxen granite
boreal ravine
#

try that ^

shadow wraith
#

i use mac tho

boreal ravine
#

well I think theres a lock icon too on mac

shadow wraith
#

yes

boreal ravine
#

yes

shadow wraith
#

you mean the "connection is secure" one?

slate swan
#

How would I get the embed title from a message in a different function

boreal ravine
shadow wraith
#

well for me it says certificate is valid lmfao

#

its named beginner.py because im a beginner at this lmfao

boreal ravine
unkempt canyonBOT
slate swan
#

Ok

unkempt canyonBOT
slate swan
#

So I’m using a library that adds components to messages and I’m trying to get the embed title of a message that is in a command function in an event

#

I have a button click event

#

And a command that sends buttons

#

I’m trying to get the embed title when the button is clicked

boreal ravine
#

same thing as I said earlier

slate swan
#

Oh shit I’m dumb

#

Sorry bruh

boreal ravine
#

👌

shadow wraith
#

this is my code btw:

import discord # discord lib colors module set
from discord.ext import commands # fuck you i dont need to explain this

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print("WTF BRO") # print when bot is online

@client.command()
async def ping(ctx):
    await ctx.send('pong')
``` there is client.run i just hid it becuase of the token
#

it wont freaking run

boreal ravine
#

hm

slate swan
#

Any errors?

#

Don't name your bot variable client, that's the first thing you should change

#

^

boreal ravine
#

well he posted it earlier and you said something about it being a pc/browser problem

slate swan
#

And yeah, any errors?

shadow wraith
#

this mess

slate swan
#

Install the certificate

shadow wraith
slate swan
#

^

shadow wraith
#

i use mac

#

yea uhh

boreal ravine
#

?

slate swan
#

Getting [SSL: CERTIFICATE_VERIFY_FAILED] on Python 3 on OS X?
Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Happy coding!

shadow wraith
#

ohhhhhh

#

im being a stupid

slate swan
#

All of them are working if used correctly

shadow wraith
#

wait wtf

#

i still have the issue

#

of sslcertificate

boreal ravine
#

how does mongodb the easiest db literally not work

#

🤔

#

How does that change anything

#

using another OS doesnt change anything

shadow wraith
#

it does actually

boreal ravine
#

what does

shadow wraith
#

theres limited crap in c language which is what python is made from

slate swan
#

Does anyone know how to use discord-components?

shadow wraith
#

i think that crap is outdated

slate swan
shadow wraith
slate swan
#

He forgor 💀

#

Is rapptz/discord.py good?

#

Idc anyway

#

I’m using discord-components

#

Nvm

#

Buttons

reef shell
#

Why not dpy v2.0 yert

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
slate swan
reef shell
#

python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py
(you need python 3.8 or later)

slate swan
#

I have 3.9 😎

reef shell
#

pip install -U git+https://github.com/Rapptz/discord.py (you need python 3.8 or later)

slate swan
#

Anyway I ran it

floral jacinth
#

could if reaction.emoji == ":one:" or ":two:" or ":three:": works or i need to do
if reaction.emoji == ":one:" or reaction.emoji == ":two:" or reaction.emoji == ":three:":

slate swan
reef shell
#

ypu might wanna check some examples

#

It's easy to use dpy 2.0 for buttons and selects

loud junco
#
moblist = {
  'mainmob' : {
    'pig' : False,
    'cow' : False,
    'sheep' : False,
    'villager' : False,
    'witherskeleton' : False,
    'blaze' : False,
    'enderman' : False
  },

  'notmainmob' : {
    'angrypig' : False,
    'zombie' : False,
    'angrycow' : False,
    'spider' : False,
    'angrysheep' : False,
    'skeleton' : False,
    'nitwit' : False,
    'pillager' : False,
    'magmacube' : False,
    'zombiepiglin' : False,
    'silverfish' : False
  }
}
###############################3
async def area(message):
  
  if area == 1:

    for item in moblist['mainmob'].values():
      item = False

    for item in moblist['notmainmob'].values():
      item = False
#

will this change all of them to false if some of them is true

reef shell
#

Here are some examples

loud junco
#

or just moblist['mainmob'] : False
moblist['notmainmob'] : False

slate swan
loud junco
#

iterate all? and put all to false

reef shell
slate swan
slate swan
slate swan
loud junco
#
for mob in moblist['mainmob']:
    mob = False

for mob in moblist['notmainmob']:
    mob = False
reef shell
slate swan
reef shell
#

and did you check the examples?

slate swan
# reef shell Show code?
from discord.ext import commands
from discord import FFmpegPCMAudio


bot = commands.Bot(help_command=None, command_prefix="j!")

@bot.event
async def on_ready():
    print('ready')
    DiscordComponents(bot)
    
@bot.event
async def on_button_click(interaction):
 
    if interaction.component.label.startswith("play"):
        channel = interaction.channel
        await channel.send(interaction.message.embeds[0].title + " " + interaction.author.mention)```
loud junco
#

print(moblist['notmainmob['pillager']')

#

is this how i do it?

reef shell
#

You didn’t even try

loud junco
boreal ravine
slate swan
reef shell
#

No, he just installed v2.0

boreal ravine
#

he was using discord-components earlier

reef shell
slate swan
#

How the hell do I add buttons 😢

boreal ravine
#

2.0

slate swan
#

Ik

loud junco
#

help

print(moblist['notmainmob['pillager']'])

this is wrong

slate swan
#

How do I add buttons

boreal ravine
#

examples folder pls

reef shell
steady flume
#

how to solve?

slate swan
#

button(label=“f”) doesn’t work anymore

reef shell
#

Check

reef shell
steady flume
reef shell
#

Did you even read the error

loud junco
#
moblist = {
    'pig' : False,
    'cow' : False,
    'sheep' : False,
    'villager' : False,
    'witherskeleton' : False,
    'blaze' : False,
    'enderman' : False,
    'angrypig' : False,
    'zombie' : False,
    'angrycow' : False,
    'spider' : False,
    'angrysheep' : False,
    'skeleton' : False,
    'nitwit' : False,
    'pillager' : True,
    'magmacube' : False,
    'zombiepiglin' : False,
    'silverfish' : False
  }

for mob in moblist().values:
    mob = False
    
print(moblist[notmainmob['pillager']])

#################################################
#Traceback (most recent call last):
 # File "<string>", line 22, in <module>
#TypeError: 'dict' object is not callable

help

slate swan
# reef shell ***Check***

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: call() missing 1 required positional argument: 'context'

#
class Confirm(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    # When the confirm button is pressed, set the inner value to `True` and
    # stop the View from listening to more input.
    # We also send the user an ephemeral message that we're confirming their choice.
    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
    async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message('Confirming', ephemeral=True)
        self.value = True
        self.stop()

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message('Cancelling', ephemeral=True)
        self.value = False
        self.stop()


bot = Bot()


@bot.command()
async def ask(ctx: commands.Context):
    """Asks the user a question to confirm something."""
    # We create the view and assign it to a variable so we can wait for it later.
    view = Confirm()
    await ctx.send('Do you want to continue?', view=view)
    # Wait for the View to stop listening for input...
    await view.wait()
    if view.value is None:
        print('Timed out...')
    elif view.value:
        print('Confirmed...')
    else:
        print('Cancelled...')
steady flume
#

huh, im nub

reef shell
#

And figure it out

#

Or show the code here

steady flume
reef shell
#

line 18

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / b
ZeroDivisionError: division by zero

The best way to read your traceback is bottom to top.

• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

reef shell
#

Send Full traceback rooMonkaS rooMonkaS

steady flume
#
class Pages(discord.ui.View):

    def __init__(self, author: int, embeds: list, embeds2: list):
        self.author = author
        super().__init__(timeout=15)
        self.embeds = embeds
        self.embeds2 = embeds2
        self.author = author
        self.embed_count = 0
        self.embed_count2 = 0
        self.response = None
        self.add_item(Menu(embeds2=self.embeds2))

    async def on_timeout(self):
        for child in self.children:
            child.disabled = True
            child.style = discord.ButtonStyle.grey
            self.children[0].emoji = ":dl_arrow:"
            self.children[1].emoji = ":dr_arrow:"
        await self.response.edit(view=self)

    async def interaction_check(self, interaction: discord.Interaction):
        if self.author == interaction.user.id:
            return True
        else:
            await interaction.response.send_message(f"This menu is not for you", ephemeral=True)

    @discord.ui.button(label=None,
                       custom_id='1',
                       style=discord.ButtonStyle.red, disabled=True, emoji=":l_arrow:", row=2)
    async def back_page(self, button: discord.ui.Button, interaction: discord.Interaction):
        if self.embed_count > 0:
            self.embed_count -= 1
            self.children[1].disabled = False
            if self.embed_count == 0:
                button.disabled = True
            await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=self)

        if self.embed_count2 > 0:
            self.embed_count2 -= 1
            self.children[1].disabled = False
            if self.embed_count2 == 0:
                button.disabled = True
            await interaction.response.edit_message(embed=self.embeds2[self.embed_count2], view=self)
#
@discord.ui.button(label=None,
                       custom_id='2',
                       style=discord.ButtonStyle.red, disabled=False, emoji=":r_arrow:", row=2)
    async def last_page(self, button: discord.ui.Button, interaction: discord.Interaction):
        if self.embed_count < len(self.embeds) - 1:
            self.embed_count += 1
            self.children[0].disabled = False
            if self.embed_count == len(self.embeds) - 1:
                button.disabled = True
            await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=self)


class Menu(discord.ui.Select):
    def __init__(self, embeds2: list):
        menus = [
            discord.SelectOption(label="Currency", default=True),
            discord.SelectOption(label="Moderation")
        ]
        super().__init__(placeholder=None, custom_id='3', min_values=1, max_values=1, options=menus, row=1)
        self.embeds2 = embeds2
        self.embed_count = 0

    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "Moderation":
            await interaction.response.edit_message(embed=self.embeds2[self.embed_count], view=self)
slate swan
# reef shell Send Full traceback <:rooMonkaS:747680279392419880> <:rooMonkaS:7476802793924198...
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 107, in djboard
    view = djboard()
TypeError: __call__() missing 1 required positional argument: 'context'

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

Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __call__() missing 1 required positional argument: 'context'```
crimson spindle
#

Hello, could someone help me get the id of a channel by a command and put it in a variable to use it, the bot is in python

here is my code

@client.command()
async def aandd(ctx):
    channel = discord.utils.get(ctx.guild.channels)
    channel_aandd_id = channel.id
    await ctx.send(channel_aandd_id)
inner geyser
#

Hey there

slate swan
inner geyser
#

can anyone tell me why

In embeds.0.fields.0.value: This field is required

this error occurs

slate swan
#
class djboard(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    # When the confirm button is pressed, set the inner value to `True` and
    # stop the View from listening to more input.
    # We also send the user an ephemeral message that we're confirming their choice.
    @discord.ui.button(label='Play', style=discord.ButtonStyle.grey)
    async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
        channel = interaction.channel
        await channel.send(interaction.message.embeds[0].title + " " + interaction.author.mention)
        await interaction.response.send_message('Confirming', ephemeral=True)
        self.value = True
        self.stop()

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message('Cancelling', ephemeral=True)
        self.value = False
        self.stop()
    
@bot.command()
async def djboard(ctx):
    view = djboard()
    e = discord.Embed(title=f'{ctx.author.name}\'s djboard | {ctx.author.id}', description="Your dj board sir")
    m = await ctx.send(embed=e, view = view)
    buttons = True
    await view.wait()
    if view.value is None:
        print('Timed out...')
    elif view.value:
        print('Confirmed...')
    else:
        print('Cancelled...')
reef shell
#

why tf you call a command like that

inner geyser
slate swan
inner geyser
slate swan
reef shell
#

view = Confirm()

slate swan
#

Field value is required

#

As simple as that

inner geyser
slate swan
#

Nope

#

Otherwise you wouldn't get the error

inner geyser
# slate swan Nope

tbh, this is a pypi package command
and this thing works with most of the packages

#

but, not with some, for ex. aiohttp

loud junco
inner geyser
slate swan
#

Well what do you put in the value of the first field of the embed

#

Print it

#

And you'll see it's sometimes empty

inner geyser
loud junco
#
moblist = {
    'pig' : False,
    'cow' : False,
    'sheep' : False,
    'villager' : False,
    'witherskeleton' : False,
    'blaze' : False,
    'enderman' : False,
    'angrypig' : False,
    'zombie' : False,
    'angrycow' : False,
    'spider' : False,
    'angrysheep' : False,
    'skeleton' : False,
    'nitwit' : False,
    'pillager' : True,
    'magmacube' : False,
    'zombiepiglin' : False,
    'silverfish' : False
  }

for mob in moblist.values():
    mob = False
    
print(moblist['pillager'])
#

output is true lmao

slate swan
loud junco
#

why is the for loop not working

slate swan
#

Because you can't do it like that

#

You need to do dict[key] = value

#

The key would be the mob name and the value False

inner geyser
#

...
wtf is that indent

slate swan
loud junco
#

alright

#

thanks lemme try

slate swan
#

!e
x = {"a":True, "b":False}
x_new = dict.fromkeys(x, False)
print(x_new)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

{'a': False, 'b': False}
slate swan
#

Yeah that's even faster

#

No need to loop

loud junco
#

alright

slate swan
inner geyser
#

btw, ur username is quite funny!

slate swan
#

Print author before the is None check

inner geyser
slate swan
#

Does your exception even get raised?

inner geyser
#

basically, here the thing is, the author thing comes as "", but I try to take it as None

#

not sure if it is right or wrong

slate swan
#

Well

#

!e
empty_string = ""
print(empty_string is None)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

False
inner geyser
#

yeah, fixed it, "" was the issue

slate swan
#

An empty string is not None

inner geyser
boreal ravine
#

anything empty is None

maiden fable
maiden fable
#

!e print("" is None)

unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
inner geyser
maiden fable
#

False ^^^

boreal ravine
#

i mean false*

maiden fable
#

Ah okay

slate swan
#
Ignoring exception in command djboard:
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 105, in djboard
    view = djboard()
TypeError: __call__() missing 1 required positional argument: 'context'

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

Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __call__() missing 1 required positional argument: 'context'
#

!e
print(len(''))

#
class Confirm(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    # When the confirm button is pressed, set the inner value to `True` and
    # stop the View from listening to more input.
    # We also send the user an ephemeral message that we're confirming their choice.
    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
    async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message('Confirming', ephemeral=True)
        self.value = True
        self.stop()

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message('Cancelling', ephemeral=True)
        self.value = False
        self.stop()
    
    
@bot.command()
async def ask(ctx: commands.Context):
    """Asks the user a question to confirm something."""
    # We create the view and assign it to a variable so we can wait for it later.
    view = Confirm()
    await ctx.send('Do you want to continue?', view=view)
    # Wait for the View to stop listening for input...
    await view.wait()
    if view.value is None:
        print('Timed out...')
    elif view.value:
        print('Confirmed...')
    else:
        print('Cancelled...')
```why, this is the exact cde from the example wtf
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

0
slate swan
#

checking its length can be a better way lemon_thinking

#

Result is the same

#

!e
print(0 == False)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

True
slate swan
#

an empty string is always False

#

It's length == 0 == False

#

does they want to check if the length is 0 and then do something ?

#

It doesn't even matter

#
def check(string):
    if not string:
        return 'string is empty'
    return 'no no empty' 




unkempt canyonBOT
#

@slate swan :warning: Your eval job has completed with return code 0.

[No output]
slate swan
#

Result is the same

boreal ravine
slate swan
#

Never called the function

boreal ravine
#

you returned it

slate swan
#

i know.

#

It will never execute KEKL

boreal ravine
#

or that

slate swan
#

its just an example joe_shrek

#

smh

#

Then why eval it

#

And edit it like 2-3 times

#

Hoping to get output

#

i edited it only once to remove the eval

#

weird

steady flume
#

how to solve?

slate swan
#

You can't use [0] on a Pages object

steady flume
#

okie

steady flume
#

no error, but nothing happens

slate swan
#

I never used views or anything similar

#

Just saying that you can't use [0] on a Pages object

#

That's basically what the error tells

steady flume
#

o ok

#

too diff

slate swan
#

how do i make a discord.ui button do something everytime it is clicked instead of it doing it conce and not doing it again#

boreal ravine
#

!d discord.ui.View.stop

unkempt canyonBOT
#

stop()```
Stops listening to interaction events from this view.

This operation cannot be undone.
boreal ravine
#

^ I think idk

crimson spindle
slate swan
#

Thankyou

crimson spindle
#

no just !welcome in a channel

slate swan
#

you’d get the ctx channel id

slate swan
#

dude

#

he said in the channel

#

They want to send in the welcome channel jeez

crimson spindle
#
@client.command()
async def aandd(ctx):
    channel = discord.utils.get(ctx.guild.channels)
    channel_aandd_id = channel.id
    await ctx.send(channel_aandd_id)
#

it's my code

#

et i want to get the id for another command

#

channel_aandd_id

slate swan
#

channel = discord.utils.get(ctx.guild.channels)

#

What channel is this supposed to be

crimson spindle
#

my command is okay, but idk how to get the var [channel_aandd_id] for another command

slate swan
#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

Maybe you can get a use of this

crimson spindle
#
@client.event
async def on_member_join(member):
    channel = client.get_channel(channel_aandd_id)
    embed = discord.Embed(title="welcome", description=f"{member.mention}", color=embedcolor)
    await channel.send(embed=embed)
    print(f"\033[1;31;40m event : member_join \033[0m")

this command

rotund nova
#
class DurationConverter(commands.Converter):
  async def convert(self, ctx, argument):
    amount = argument[:-1]
    unit = argument[-1]

    if amount.isdigit() and unit in ['s', 'm', 'h', 'd']:
      return (int(amount), unit)

    raise commands.BadArgument(message='Not a valid duration')

@bot.command(name='mute')
@commands.has_any_role("𝙊𝙒𝙉𝙀𝙍 👑","🔧│Developer-dc","𝙈𝙊𝘿","𝘼𝙙𝙢𝙞𝙣")
async def tempmute(ctx, member: commands.MemberConverter, duration: DurationConverter, reason=None):
  channel = bot.get_channel(901138355239157811)


  multiplier = {'s': 1, 'm': 60, 'h': 3600}
  amount, unit = duration

  guild = ctx.guild
  mutedRole = discord.utils.get(guild.roles, name="Muted")



  if not mutedRole:
    mutedRole = await guild.create_role(name="Muted")

    for channel in guild.channels:
      await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)

  await member.add_roles(mutedRole, reason=reason)

  embed = discord.Embed(title=f'Wyciszony!', description=f"{member.mention} został wyciszony. ", colour=0xb133ff)
  embed.add_field(name="Powód:", value=reason, inline=False)
  embed.add_field(name="Wyciszenie zostanie usunięte za:", value=f"{amount}{unit}", inline=False)
  channel = await member.create_dm()
  ban = discord.Embed(title=f" Zostałeś/-aś wyciszony/-a na serwerze McForever.eu, {member.name}", description=f" Powód: {reason}\n Na: {amount}{unit}\nZmutował: {ctx.author.mention}\n\n **Jak otrzymać unmute?**\n Napisz do osoby powyżej, która cię wyciszyła aby się odwołać (albo osóby z wyższą rangą).", color=0xb133ff)  
  await channel.send(embed=ban)
  await ctx.send(embed=embed)
  await asyncio.sleep(amount)
  await member.remove_roles(mutedRole)
``` why bot dont wait when time end and give automaticly unmute
slate swan
#

Then you can save it and use everywhere you want

crimson spindle
#

no that dont work

slate swan
crimson spindle
#

okay wait

#

just

slate swan
#

I get what you want to do

#

Just answer that question

#

You want to do !welcome and it saves the id of the current channel so that the welcome messages are sent in that channel

crimson spindle
#
joinchannel = channel_aandd_id

@client.event
async def on_member_join(member):
    channel = client.get_channel(joinchannel)
    embed = discord.Embed(title="welcome", description=f"{member.mention}", color=embedcolor)
    await channel.send(embed=embed)
    print(f"\033[1;31;40m event : member_join \033[0m")

@client.command()
async def aandd(ctx):
    channel = discord.utils.get(ctx.guild.channels)
    channel_aandd_id = channel.id
    await ctx.send(channel_aandd_id)
#

but that dont work

boreal ravine
#

isnt channel_aandd_id a local variable

slate swan
#

It is

#

That's why I said to use bot variables...

crimson spindle
slate swan
#

That's your issue, it's local

#

It should be local

#

Use a bot variable

#

Then you can use bot.welcome_channel_id everywhere

slate swan
crimson spindle
#

how ?

slate swan
crimson spindle
#

yees i know this but i want to get an id channel to put in the local variable

slate swan
#

You said you already have the command working and sending the channel id

crimson spindle
#

yes but .. the variable doesn't accept my variable [channel_aandd_id]

slate swan
#

Does the correct channel id get sent?

crimson spindle
#
joinchannel = [HERE, it's doesn't work]

@client.event
async def on_member_join(member):
    channel = client.get_channel(joinchannel)
    embed = discord.Embed(title="welcome", description=f"{member.mention}", color=embedcolor)
    await channel.send(embed=embed)
    print(f"\033[1;31;40m event : member_join \033[0m")

@client.command()
async def aandd(ctx):
    channel = discord.utils.get(ctx.guild.channels)
    channel_aandd_id = channel.id
    await ctx.send(channel_aandd_id)
slate swan
#

As I said 3 times

#

Use. Bot. Variables.

#
bot = commands.Bot(...)

bot.channel_id = default welcome channel id i guess

# In your event you can use bot.channel_id to get the channel id and send to it

@bot.command()
async def welcome(ctx):
    bot.channel_id = the channel new id
crimson spindle
#

mmh okay sorry

velvet tinsel
#

Guys

#

Wait

#

How do you use error handlers again

slate swan
#

For specific commands?

velvet tinsel
#

yes

velvet tinsel
#

@reef shell Mentioned something about a GIST

boreal ravine
slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 96, in play
    message = await interaction.channel.send("playing music! " + interaction.author.mention)
AttributeError: 'Interaction' object has no attribute 'author'``````py
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey)
    async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
        message = await interaction.channel.send("playing music! " + interaction.author.mention)``` why
#

it was working before

#

😢

crimson spindle
boreal ravine
#

👍

slate swan
#

@vocal plover Small question, are these indents made on purpose for copy paste or not?

boreal ravine
#

probably on purpose

slate swan
#

I don't want a "probably" answer, thanks

slate swan
fervent surge
#

I am switching to use falixnodes to host my discord bot. I think that it is a linux server powered by AMD Ryzen. My server is, i think a docker image. I installed all of the requirements, but I get an error: py line 77: ansyc def on_ready() ^ Invalid syntax I am using 3.8.8

slate swan
slate swan
velvet tinsel
#

why isn't this working

#
    try:
        users = await get_bank_data()
        user = ctx.author
        wallet_amt = users[str(user.id)]["wallet"]
        bank_amt = users[str(user.id)]["bank"]
        await open_account(ctx.author)

        earnings = random.randint(300, 550)
        person = ["Steve", "Karen", "Micheal", "Daniel Craig", "Donald Trump", "Joe Biden", "Elon musk", "Jake", "Dank Memer"
                      "Rick Astley", "Drake", "Jerry", "Anonymous"]
        choice = random.randint(1, 2)
        if choice == 1:
            earning_embed = discord.Embed(title="Success!", description=f"\"Oh, you poor little beggar, here's {earnings} dogecoin(s)!\" \n-{random.choice(person)}", color=discord.Color.green())
            users[str(user.id)]["wallet"] += earnings

            with open("mainbank.json", 'w') as f:
                    json.dump(users, f)
            await ctx.send(embed=earning_embed)
        else:
            responses = ["Imagine begging", "BRO GET A JOB", "Sorry I don't have money", "Nahhhhhh", "Get good", "coin.exe has stopped functioning.Please try again later", "What", "Stop your gambling addiction"
                             "how about a **no**.", "I lost money from you earlier."]
            no_embed = discord.Embed(title="Failure", description=f"{random.choice(responses)}. \n-{random.choice(person)}", color=discord.Color.red())
            await ctx.send(embed=no_embed)
    except discord.ext.commands.errors.CommandOnCooldown:
        await ctx.send("You are on cooldown")
slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
velvet tinsel
#
Ignoring exception in command beg:
Traceback (most recent call last):
  File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\core.py", line 788, in prepare
    self._prepare_cooldowns(ctx)
  File "C:\Users\\PycharmProjects\Doge\venv\lib\site-packages\discord\ext\commands\core.py", line 772, in _prepare_cooldowns
    raise CommandOnCooldown(bucket, retry_after)
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 24.72s
#

sad nois

slate swan
#

aint it obvious?

velvet tinsel
#

yes

slate swan
#

you're on a cooldown

velvet tinsel
#

but I did except

#

is it the except problem?

slate swan
#

that function does not get called if you're on a cooldown

velvet tinsel
#

oh

thick sigil
#

Hes a computer developer and can create nft generation code, python is too hard for his skills

velvet tinsel
#

Then how do I send "you are on cooldown"

slate swan
#

use on_command_error if you want to send something like "you are on a cooldown"

velvet tinsel
#

Ok

slate swan
#

its an event

thick sigil
#

And u cant do basic things

velvet tinsel
boreal ravine
velvet tinsel
boreal ravine
vocal plover
velvet tinsel
#

Haha copy paste go brrr

#

I wonder how they do the py thing

#

But if someone creates a new language

#

How would they paste code

boreal ravine
#

what py thing

velvet tinsel
#

Python in discord

boreal ravine
velvet tinsel
slate swan
velvet tinsel
#

Asnyc

boreal ravine
#

asnyc

slate swan
sick veldt
#

Hello

#

I need help in my code

vocal plover
slate swan
#

hmm okay

slate swan
#

So basically indented with the code that comes before that part of code, which is not in that code block

vocal plover
#

tho this reminds me I need to cause myself pain and try to remove the copy button in the compose theme

boreal ravine
unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / b
ZeroDivisionError: division by zero

The best way to read your traceback is bottom to top.

• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

steady flume
#

how to edit embed in Select view ?
await interaction.message.edit() - i tried this, it changed page, but selection doesnt change

boreal ravine
#

you cant edit a select menu

steady flume
slate swan
#

Anyways, you have a great day 2DRenownThumbsUp

rotund nova
steady flume
#

but i send embed and when i want choose selection - it must change this embed, it change, but select option doesnt change

boreal ravine
slate swan
#

why bot dont wait when time end and give automaticly unmute
@boreal ravine There is none, ^

#

Have you tired to print amount?

rotund nova
slate swan
rotund nova
boreal ravine
#

hm

sick veldt
#

can anyone help me

slate swan
# rotund nova ?

Since it doesn't wait, try to print the variable amount that you give when using asyncio.sleep.....

sick veldt
#

Traceback (most recent call last):
File "main.py", line 18, in <module>
client.run(os.getenv('TOKEN'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'

slate swan
slate swan
#

In the bot/client.run

slate swan
#

bot/client.run("token")

sick veldt
#

lemme try

#

where shall i put it?

slate swan
#

I mean,

#

You coded your bot didn't you?

rotund nova
sick veldt
#

Coding

slate swan
#

And since os.getenv("TOKEN") is None, then to need to create an environment variable called TOKEN and give the bot token as value

#
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey)
    async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("playing music! " + interaction.user.mention)
            
``` how can i delete the message that is sent (await messsage.delete doesnt work)
#

nvm

#

or just use the delete_after kwarg when sending the message

boreal ravine
#

hm

slate swan
#

Do this.

@bot.command()
async def hiThere(ctx):
  pleaseDontTouchMe = await ctx.send("D")
  pleaseDontTouchMe.delete()
#

So that doesn't work?

dapper cobalt
boreal ravine
#

he probably uses javascript

slate swan
#

Someone said it is still possible

boreal ravine
#

who said it isnt??

dapper cobalt
#

!pypi dislash.py is a good 3rd party library for that.

unkempt canyonBOT
rotund nova
#

@slate swan so what do

slate swan
#

my bot creates a ticket on reaction, and sends a message in that ticket channel which has a reaction

#

how do i capture that reaction?

#

Is there a way to make the bot send unicode emojis?
Right now for eg it sends
🙄 even if I want it to send \🙄

#

Hi evreone

slate swan
#

can you give ideas discord bot plz

boreal ravine
#

make a bot where it connects with fornite!!

rotund nova
#

@boreal ravine what do?

boreal ravine
#

idk

slate swan
#

!d discord.ui.button

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
boreal ravine
#

disabled kwarg interesting

slate swan
#

how do i usw wmojis in my buttons

#

I finally did it

boreal ravine
slate swan
#

The button...

boreal ravine
slate swan
#

it has an emojis kwarg

#

IT WORKED!!!!

boreal ravine
slate swan
boreal ravine
slate swan
#

k

slate swan
#

are custom emojis allowed in buttons?

#

🤔 i doubt they are not

boreal ravine
#

they are who says you cant

slate swan
#

mhm it takes a PartialEmoji object as an argument

boreal ravine
slate swan
#
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body  
In components.0.components.0.emoji.name: Invalid emoji
In components.0.components.1.emoji.name: Invalid emoji
In components.0.components.2.emoji.name: Invalid emoji`````py
oak falcon
#

hi guys, need some help here: #help-grapes , can someone have a look?

oak falcon
boreal ravine
slate swan
#

i want to use ⏸️ ▶️ and ❌

oak falcon
#
emoji = get(bot.get_guild(guild_id).emojis, name="name_of_your_emoji")```
slate swan
#

i have put the names of these emojis in but its bot working

boreal ravine
slate swan
#
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey, emoji="arrow_forward")
    async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("playing music! " + interaction.user.mention)
            time.sleep(5)
            await message.delete()
        
        

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Pause', style=discord.ButtonStyle.grey, emoji="pause_button")
    async def pause(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("Paused music! "  + interaction.user.mention)
            time.sleep(5)
            await message.delete()
            
    

    @discord.ui.button(label='Quit', style=discord.ButtonStyle.grey, emoji="x")
    async def quit(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("Quiting out of djboard! " + interaction.user.mention)
            
            self.stop()
            await interaction.message.delete()
            time.sleep(5)
            await message.delete()
#

k

#

isnt there a place in this server to get unicode for emojis?

dapper cobalt
#

!unicode

#

I forgot the command.

slate swan
#

unicode?

#

🤣

boreal ravine
#

!unicode ⏸️

#

hm

slate swan
#

oh wait

#

embed fail

boreal ravine
#

ip grabber no clicking that

oak falcon
dapper cobalt
#

!charinfo ⏸️

unkempt canyonBOT
slate swan
#

since its a discord emoji it has assests in it just a sec

#

!charinfo ❌

unkempt canyonBOT
slate swan
#
https://cdn.discordapp.com/emojis/759569537908867072.png?size=96```
#

there is the code in the url

#

!charinfo ⏸️

unkempt canyonBOT
slate swan
#

!charinfo ▶️

unkempt canyonBOT
slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 423, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction``` i get this error but nothing wrong is happening, how do i stop thsi error because i want clean terminal
slate swan
#

can someone help me to make to a fight command which makes people to fight each other by using moves such as kick,block,punch and each thing having its own value
i have made a json dic for that purpose so can anyone help me out?

#

any help pls?

#

you may be using <bot object>.wait_for('message') to check the kick block punch etc messages from the members in the game

#

with a check making sure its only from the author

#

deleted message

haughty quartz
#
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
``` what can i do about this
vocal plover
#

wait

vocal plover
#

and dont make so many api calls

haughty quartz
#

how

vocal plover
#

by not calling the api

slate swan
#

you can make only 50 api reqs in a second

#

wtfd r u even trying to do

haughty quartz
#

yeah but i think i dont do so many in a second

hazy dune
#

How long does in usually take till new features, like the Discord events get implemented into the API?

vocal plover
#

well, you do

slate swan
haughty quartz
#
@bot.command(name="t")
async def tDef(ctx, *, userinput):
  usersearch = "+".join(userinput.split())
  baseurl = 'https://www.timeanddate.com'
  url = baseurl + "/worldclock/?query=" + usersearch
  request_page = urlopen(url)
  page_html = request_page.read()
  request_page.close()
  html_soup = BeautifulSoup(page_html, 'html.parser')
  searchtz = html_soup.find(id='p0')
  if searchtz == None:
    url2 = baseurl + '/worldclock/' + usersearch
    request_page2 = urlopen(url2)
    page_html2 = request_page2.read()
    request_page2.close()
    html_soup2 = BeautifulSoup(page_html2, 'html.parser')
    searchtz2 = html_soup2.find(id='mp0')
    await ctx.send(" ".join(searchtz2.string.split())[3:])
  else: 
    await ctx.send(" ".join(searchtz.string.split())[3:])
#
import os
import discord
from discord.ext import commands
from urllib.request import urlopen
from bs4 import BeautifulSoup

#

any idea why i have so many api calls

#

?

oak falcon
#

guys how can I use item callbacks and interactions?

slate swan
oak falcon
#

do you have one?

slate swan
#

what r u using for interactions?

oak falcon
#

ok, I am just trying to create selectMenu

#

discord.ui.Select or discord.ui.SelectMenu

#

and if user selects role, do add him this role so he can see the channels he selected

slate swan
slate swan
#

or , use replit?

haughty quartz
slate swan
# haughty quartz yes

ah so , even if you dont get ratelimited , you do

replit uses shared ips
so basically even if someone else gets ratelimited 'due to you using the same ip you face it too

slate swan
slate swan
#

i use heroku

haughty quartz
#

where can i host my bot

slate swan
#

free mostly 24/7 and good

loud junco
#
@client.event
async def on_ready(message):
    print('We have logged in as {0.user}'.format(client))
    await message.channel.send('Hello there')
#

can someone help me

loud junco
#

i wanna do that

slate swan
haughty quartz
loud junco
#

when the bot is ready it will send hello there

slate swan
#

you would be using get_channel to get the channel you need

#

and send message

#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

and .send()

loud junco
#

how do i get the id of the channel

slate swan
unkempt canyonBOT
loud junco
#

i need to define a new function for that?

slate swan
#

you dont need to , just copy it from discord and paste it there

#

Ah, nevermind, I'm guessing you're asking how you find the id of a channel from discord

reef shell
slate swan
loud junco
#

oo

reef shell
#

if you have the channel object then you can access the id attribute

loud junco
#

developer mode right?

slate swan
#

yessir

loud junco
#

alright

haughty quartz
#

What are pipelines @slate swan

#

at heroku

loud junco
slate swan
reef shell
loud junco
#

now i need to write the get_channel thing

#

someone help

hazy dune
#

How long does in usually take till new features, like the Discord events get implemented into the API?

hazy dune
#

wdym?

slate swan
#

they stopped working on it

slate swan
slate swan
slate swan
hazy dune
#

so i'd have to create an own API call for that feature?

slate swan
#

or migrate to a maintained library

#

pycord seems to be the go-to

hazy dune
#

Ok, Thanks!

slate swan
hazy dune
#

Seems like it will take some time till its implemented

slate swan
#

please let me know if you find it eiscookie

loud junco
#
channel = client.get_channel(channel_id)
await channel.send('Hello there')
slate swan
loud junco
#

where do i add this thing

slate swan
#

like on_ready

loud junco
#

inside on_ready?

slate swan
#

yes#

loud junco
#

alright thanks

slate swan
#

yes

oak falcon
#

guys, how can I install Rapptz discord.py in version 2.0? I did get some link from someone, but I would like to install it on another machine and I cannot find the link

#

to clone proper one

slate swan
#

Go to the rapptz homepage on github

#

And copy th command to install it

oak falcon
#

it has the latest version on master branch?

slate swan
#

yes

slate swan
#

make sure you have git installed

oak falcon
#

thx

#

but then I have 1.7.3 and I want 2.00

slate swan
#

yeah it will update it ( -U will do that)

oak falcon
#

ahh ok

#

I did not see it

slate swan
#

How can I remove “this interaction failed” message

oak falcon
#

no idea, but I saw there is is_finished() and on_timeout(), then you can disable those buttons and the message will not show up

#

when view times out you can make button disabled

#

but I did not find yet a way to remove this shit

#

I did not try it yet thou

oak falcon
slate swan
oak falcon
#

no no

slate swan
#

oh

#

confirm what works?

oak falcon
#

how can you work with buttons not to see this interaction failed message

slate swan
oak falcon
#

yes, this shit

slate swan
#

yes

#

how do i stop it

oak falcon
#

I proposed you disable buttons when on_timeout or is_finished()

#

or you coudl edit the message

slate swan
#

i dont disable the buttons

oak falcon
#

ok, maybe edit the message

slate swan
#
 @discord.ui.button(label='Play', style=discord.ButtonStyle.grey, emoji="\u25b6")
    async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("playing music! " + interaction.user.mention)
            time.sleep(5)
            await message.delete()
        
        

    # This one is similar to the confirmation button except sets the inner value to `False`
    @discord.ui.button(label='Pause', style=discord.ButtonStyle.grey, emoji="\u23f8")
    async def pause(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("Paused music! "  + interaction.user.mention)
            time.sleep(5)
            await message.delete()
            
    

    @discord.ui.button(label='Quit', style=discord.ButtonStyle.grey, emoji="\u274c")
    async def quit(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            message = await interaction.channel.send("Quiting out of djboard! " + interaction.user.mention)
            
            self.stop()
            await interaction.message.delete()
            time.sleep(5)
            await message.delete()
oak falcon
#

then you refresh the timeout

slate swan
#

thats my button code

oak falcon
#

in the docs

slate swan
#

👀

#

its that not big of a deal anway

oak falcon
#

you have:

slate swan
#

i have stop()

oak falcon
#

but when the message appears you still get what you want on callback?

slate swan
#

yes

oak falcon
#

that is strange then, maybe try to make it persistent?

#

then timeout it None

#

so it should stay alive

slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 423, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction``` ```py@bot.command()
async def djboard(ctx: commands.Context):
    
    view = Djboardcommand()
    e = discord.Embed(title=f'{ctx.author.name}\'s djboard | {ctx.author.id}', description="Your dj board sir")
    m = await ctx.send(embed=e, view = view)

@djboard.error
async def djboard_error(ctx, error):
    if isinstance(error, discord.errors.NotFound):
        return```
#

why am i still getting the error even though ium handeling it

#

o wait

#

i need to handle it on the buttons

oak falcon
#

seems that your interaction is not known, I guess you need some kind of ID for it or some ref

heavy folio
#

guys what are your thoughts on mongodb, is it safe or not

#

people tell me its easy to hack and it isnt safe

oak falcon
#

python recommends postgres

loud junco
#

how do i make probability

oak falcon
slate swan
loud junco
#

like drop rate

grim oar
#

random module

loud junco
#

import random?

slate swan
#

yes

loud junco
#

pls do the module command

grim oar
#

!d random

unkempt canyonBOT
#

Source code: Lib/random.py

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

loud junco
#

thanks

oak falcon
slate swan
#

could you sample some code?

loud junco
#

random module doesnt have probability ;-;

slate swan
#
@bot.command()
async def lock(self, ctx, member: discord.Member):
  guild = ctx.guild
  lockedrole = discord.utils.get(guild.roles, name="lockedrole")
  if not lockedrole:
    lockedrole = await guild.create_role(name="lockedrole")
    await member.add_roles(lockedrole)
  for channel in guild.channels:
    
    await channel.set_permissions(lockedrole, speak=False, send_messages=False, read_message_history=True, read_messages=True, add_reactions=True)
    await ctx.send("Locked")
loud junco
slate swan
#

its a test lock i've never did it again

slate swan
slate swan
#

chances*

slate swan
# slate swan ?

it doesnt lock the channel

its a test lock i've never did it again

loud junco
#

i dun und what that website says

slate swan
#

ok

#

does it work

loud junco
#

idk how to use that

#

thats the problem

slate swan
#
import random

if random.random() < percentage_chance:
    print('aaa')
loud junco
#

random.random()?

visual island
#

!d random.choices for choices with probability

unkempt canyonBOT
#

random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").

If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
loud junco
slate swan
#
import random

if random.random(0,100) < 34:
    print('aaa')
if 67 > random.random(0,100) > 33 :
    print('aaa')
if  101 > random.random(0,100) > 66:
    print('aaa')
loud junco
#

alright

#

thanks

#

this is pretty helpful

#

can i dm u for help?

slate swan
#

sure

loud junco
#

thankss

slate swan
#

hello

slate swan
#

yes

heavy folio
slate swan
oak falcon
slate swan
heavy folio
#

oh

#

but what do you guys think bout mongodb

slate swan
#

because that wont return integers

oak falcon
heavy folio
#

oh

oak falcon
#

does Rapptz provide examples for discord 2.0?

oak falcon
#

where?

slate swan
# slate swan what?

actually i was making a code that each time my bot sees the string "I'm bored" it will ask to say a joke and each time you say no it gives the yes output

#

examples folder in master branch

slate swan
#

okay

oak falcon
#

thx

#

I go eat 😛

slate swan
#
if(message == "Im bored"):
    channel.send("joke funny")
#

thats in the on_message(message)

#

event

#

yes

#

okay

#

channel = bot.get_channel(id)

#

to get the channel

#

or message.channel

#

okay thx

sudden steppe
#

Hi Guys How To Write @buttons.click in cog
Pls Help Me

slate swan
#

how do i check a reaction in a specific channel??

oak falcon
oak falcon
slate swan
#

how?

#

how to filter it

oak falcon
#

1 sec

#

I do like this:

#
 
@bot.event
async def on_raw_reaction_add(payload):
    if payload.channel_id not in omit_channels:
          <some code>
slate swan
#

but what if i want in only one channel?

#

lets say general

oak falcon
#

if payload.channel_id == your_channel_id

slate swan
#

oh so if i have a channel object name new_channel
if payload.channel_id == new_channel_id:

#

right?

oak falcon
#

wait

#

if isinstance(new_channel, discord.TextChannel):
if payload.channel_id == new_channel['id']

slate swan
oak falcon
#

can you show the error you are getting?

oak falcon
#

or you can you get()

#

new_channel.get('id')

#

or you can also ensure it has this attr

#

if isinstance(new_channel, discord.TextChannel) and hasattr(new_channel, 'id'):

#

no

#

if it is TextChannel it has id

#

so no sense to check it

slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 423, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction``````py
@bot.event
async def on_error(ctx, error):
    if isinstance(error, discord.errors.NotFound):
        m = await ctx.send("something has went wrong...")
        time.sleep(5)
        await m.delete()``` im handeling it and its still throwing the error ![lemon_grumpy](https://cdn.discordapp.com/emojis/754441880158339132.webp?size=128 "lemon_grumpy")
slate swan
cloud dawn
oak falcon
cloud dawn
#

this No idea what this is.

slate swan
unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

cloud dawn
#

!d discord.ext.commands.Bot.on_command_error

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.
oak falcon
#

@slate swan did you try to check view.is_finished() before handling interaction?

slate swan
#

What

slate swan
oak falcon
#

hmmm

#

one sec, I have to try it

cloud dawn
oak falcon
#

I have to test it 1st

slate swan
#
    @commands.Cog.listener()
    async def on_guild_role_delete(self, role):
        db = sqlite3.connect(f"{role.guild.id}.db")
        cursor = db.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS suggestionschannel(guild_id INT, channel_id)")
        cursor.execute(f"SELECT role_id FROM mutedrole WHERE guild_id = {role.guild.id}")
        wynik = cursor.fetchone()
        if wynik:
            if role.id == wynik[0]:
                cursor.execute(f"DELETE role_id FROM mutedrole WHERE role_id = ?", (role.id))
                print("Dziala")
======================================================================

Traceback (most recent call last):
  File "/home/kr3mu/.local/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "/home/kr3mu/Pulpit/AxisBOT/Eventy/roledelete.py", line 22, in on_guild_role_delete
    cursor.execute(f"DELETE role_id FROM mutedrole WHERE role_id = ?", (role.id))
sqlite3.OperationalError: near "role_id": syntax error
slate swan
oak falcon
cloud dawn
oak falcon
#

you need to define which one

#

new_channel = bot.get_channel(1024129854612421)

#

where the number is channel id

#

or you can just use the ID directly

slate swan
oak falcon
#

then payload.channel_id == 0312953095732095792

slate swan
#

but i cant know the id beforehand

oak falcon
#

to obtain ID

slate swan
#

it makes it on the go

oak falcon
#

right click on the channel and "Copy ID" on the bottom

slate swan
#

new_channel = client.get_channel(what to put there)

oak falcon
#

ID

slate swan
#

its like a temp channel

cloud dawn
slate swan
#

the bot makes it

oak falcon
slate swan
#

no i dont have that channel now

oak falcon
slate swan
#

its like a temp channel

oak falcon
#

ok

slate swan
#

ticket channel

#

that that bot will make when a user asks it

oak falcon
#

then you need to get it when you create_channel

restive abyss
#

Anyone know how to fix: KeyError: '331000144273342464' I have not found anything online (Python)

oak falcon
#

or whatever the method is named

slate swan
oak falcon
#

it should return the channel

slate swan
oak falcon
#

then you use get or dict to get ti

#

yes

slate swan
#

how do i do it?

oak falcon
#

I am not getting what you want

slate swan
oak falcon
#

dropdown_view.timeout = None

#

you need to set timeout to None

#

then interaction will not die

slate swan
#

how do i do that?

oak falcon
#

lets go pvt

cloud dawn
slate swan
slate swan
#

still trying to understand

steady flume
#

guys, can i make if self.values[0] == "Moderation":, which from Select class in Views class ??

cloud dawn
oak falcon
#

right after you select a button?

slate swan
#

thanks

steady flume
#

i mean menu

#

yes

slate swan
oak falcon
#

so this is occuring always?

cloud dawn
slate swan
slate swan
oak falcon
#

each time you click?

slate swan
#

Yes

oak falcon
#

hmmm

steady flume
river kindle
#

I'm creating a giveaway command, only it doesn't work as expected

code:

async def giveaway (ctx, time = None, *, prize = None):
  if time == None:
    return await ctx.send ("Include a ** duration **!")
  elif prize == None:
    return await ctx.send ("Please enter a ** price **!")
  embed = discord.Embed (title = 'Giveaway!', description = f '{ctx.author.mention} created a ** giveaway ** || Price: ** {prize} **')
  time_convert = {"s": 1, "m": 60, "h": 3600, "g": 86400}
  gawtime = int (time [0]) * time_convert [time [-1]]
  embed.set_footer (text = f 'The giveaway ends in: {time}')
  gaw_msg = await ctx.send (embed = embed)

  await gaw_msg.add_reaction (": tada:")
  await asyncio.sleep (gawtime)

  new_gaw_msg = await ctx.channel.fetch_message (gaw_msg.id)

  users = await new_gaw_msg.reactions [0] .users (). flatten ()
  users.pop (users.index (client.user))

  winner = random.choice (users)

  await ctx.send (f "YAY! {winner.mention} won the ** giveaway ** || Price:` {prize} `")```

error:
from the console no one, only that when I enter the time and it expires, it does not send any notification, then it 
does not add the reaction to participate in the giveaway
oak falcon
#

ok, so it is different issue

slate swan
#

Ig

steady flume
#
class Menu(discord.ui.Select):
    def __init__(self, embeds: list, embeds2: list):
        self.menus = [
            discord.SelectOption(label="Currency", default=True),
            discord.SelectOption(label="Moderation")
        ]
        super().__init__(placeholder=None, custom_id='3', min_values=1, max_values=1, options=self.menus, row=1)
        self.embeds = embeds
        self.embeds2 = embeds2
        self.embed_count = 0

    async def callback(self, interaction: discord.Interaction):
        assert self.view is not None
        view: Menu = self.view
        if self.values[0] == "Moderation":
            self.menus[0].default = False
            self.menus[1].default = True
            await interaction.response.edit_message(embed=self.embeds2[self.embed_count], view=view)
        elif self.values[0] == "Currency":
            self.menus[0].default = True
            self.menus[1].default = False
            await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=view)

my Selct class

cloud dawn
slate swan
#

what?

steady flume
#
@discord.ui.button(label=None,
                       custom_id='2',
                       style=discord.ButtonStyle.red, disabled=False, emoji=":r_arrow:", row=2)
    async def last_page(self, button: discord.ui.Button, interaction: discord.Interaction):
        if self.embed_count < len(self.embeds) - 1:
            self.embed_count += 1
            self.children[0].disabled = False
            if self.embed_count == len(self.embeds) - 1:
                button.disabled = True
            await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=self)

my button for pagination, i want if self.values[0] == "Moderation": this condition in this button

slate swan
#

😔 i dont get it

oak falcon
slate swan
#

i just want chanel id of my newly created channel

oak falcon
#

or lets take some help channel @slate swan

oak falcon
slate swan
#

the channel is made yes

#

but how do i get its id

oak falcon
#

@slate swan let me know, this is interesting for me as I am doing something similar now

oak falcon
slate swan
#

like that

oak falcon
#

so new_channel should have id

slate swan
#

curchannel is message.channel

cloud dawn
# slate swan

Well new_channel already is the text channel object.
No need to get/fetch it really

slate swan
#

yes how do i capture it

slate swan
#

just want to get its id

#

how do i get its id

cloud dawn
slate swan
#

and how do i get payload channel id

#

so i can compare them

cloud dawn
#

Can this event occur in a user DM?

slate swan
#

no

#

never

cloud dawn
#

Then payload.reaction.message.channel.id should suffice

slate swan
#

thank you!

cloud dawn
#

I really recommend using the docs since i did not knew this either i just searched it.

slate swan
cloud dawn
slate swan
#

How are people finding this out now? It's so late lmao

cloud dawn
slate swan
#

Yeah disnake is the best

#

never heard of it

cloud dawn
#

And make everything slash commands. Since those will be mandatory later anyways.

slate swan
#

will try

#

!pypi disnake

unkempt canyonBOT
slate swan
#

oo

slate swan
#

better now?

cloud dawn
#

Looks good

slate swan
cloud dawn
#

(Yes i know but im asking you)

slate swan
#

i am inspecting my code

#

but ..how could it be

#

gotcha!!

#

Here's a better example than that

#

wait lemme fix it

#

!e ```py
a = 0
if a == 1:
b = 2

print(b)

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | NameError: name 'b' is not defined
slate swan
#

Wait

#

Shouldn't that raise the unbound local error

cloud dawn
#

!e ```py
x = 10
def foo():
print(x)
x += 1

foo()

unkempt canyonBOT
#

@cloud dawn :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 |   File "<string>", line 3, in foo
004 | UnboundLocalError: local variable 'x' referenced before assignment
slate swan
#

now it doesnt get triggered

slate swan
slate swan
cloud dawn
#

Debugging is your best friend

slate swan
#

i think i know a fix wait

cloud dawn
#

Please use your own help channel, don't send your error in multiple places.

slate swan
#

okay i am stuck

cloud dawn
#

Me too

slate swan
#
async def on_raw_reaction_add(payload):
  if payload.member != client.user:
        if payload.message_id in dict_of_colour_codes.values() :
            await curchannel.send('hey hey it works')
            new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')

        if payload.channel_id == new_channel.id:
                await curchannel.send('well done')
                print("part 2 was triggered")
cloud dawn
#

if payload.message_id in dict_of_colour_codes.values() : how can this ever be true?

slate swan
#

ah it works

#

problem is last if statement

slate swan
cloud dawn
slate swan
#

whaat

#

😭 show me the light

cloud dawn
# slate swan ```py async def on_raw_reaction_add(payload): if payload.member != client.user...
async def on_raw_reaction_add(payload):
    if payload.member != client.user:
        if payload.message_id in dict_of_colour_codes.values() :
            await curchannel.send('hey hey it works')
            new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')

            if payload.channel_id == new_channel.id:
                await curchannel.send('well done')
                print("part 2 was triggered")
``` this is how it should be indented.
#

This can also be shorter

slate swan
#

whats different

cloud dawn
#
async def on_raw_reaction_add(payload):
  if payload.member != client.user and payload.message_id in dict_of_colour_codes.values():
      await curchannel.send('hey hey it works')
      new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')

      if payload.channel_id == new_channel.id:
          await curchannel.send('well done')
          print("part 2 was triggered")
cloud dawn
slate swan
#

ah

slate swan
#

rip