#discord-bots

1 messages · Page 673 of 1

upbeat otter
#

i saw the live show

maiden fable
#

Weirddd

jovial osprey
#

thx

stiff nexus
#

help?

boreal ravine
#

hm

quick gust
#

why are u sending the message inside for 😭

shadow wraith
#

one second let me see if this exists

slate swan
#

how do I get a unicode of a custom emoji

boreal ravine
#

custom emoji's dont have a unicode value

quick gust
boreal ravine
#

yeah what infernum said

slate swan
#
@bot.command()
async def test(ctx):
    message = await ctx.send('test')
    emoji = 'rick_roll:'
    await message.add_reaction(emoji)
    await ctx.add_reaction(emoji)

error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji

quick gust
#

what did I say....

quick gust
slate swan
#

i tried both the ways

upbeat otter
unkempt canyonBOT
slate swan
#

<:name:id>
or <name🆔>

quick gust
#

the one I said should work as long as the bot is in the server of the emoji

slate swan
quick gust
#

yeah then add it to your server

#

where the bot is

slate swan
quick gust
#

I'm not sure I understood that correctly

shadow wraith
#

guys i use the discord_slash module to make slash commands but whenever i tried to run my bot i got this error

#
om_type
    if issubclass(t, discord.abc.User): return cls.USER
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/abc.py", line 102, in __subclasscheck__
    return _abc_subclasscheck(cls, subclass)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/typing.py", line 1108, in _proto_hook
    raise TypeError("Protocols with non-method members"
TypeError: Protocols with non-method members don't support issubclass()
#

here is my code

#
@slash.slash(name = 'eliminate', description = 'Eliminate someone from a simon says game')
async def eliminate(ctx: SlashContext, member: discord.Member):
    guild = member.guild
    if ctx.channel.id == 919563757204693103:
        if guild.get_role(919571300467474543) in ctx.author.roles:
            if guild.get_role(919570782185750578) in member.roles:
                await member.remove_roles(919570782185750578)
                await ctx.send("{0} was eliminated! R.I.P".format(member.name))
    else:
        await ctx.message.delete()
visual island
astral cobalt
#

How do I play an mp3 with my bot?

shadow wraith
astral cobalt
#

audio_source = discord.FFmpegPCMAudio(executable="path/to/name.exe", source="path/to/name.mp3")

visual island
#

!d discord.VoiceClient.play

unkempt canyonBOT
#

play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource").

The finalizer, `after` is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.
shadow wraith
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

shadow wraith
#

my traceback is too big

astral cobalt
#

@visual island I dont think thats what I was looking for, im just getting this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: test.mp3 was not found.

#

and its from this line audio_source = discord.FFmpegPCMAudio(executable="test.exe", source="test.mp3")

slate swan
#

e.g. dank memer

quick gust
#

yes because the emojis they use are in a server where the bot is aswell

quick gust
#

Np

heavy folio
#

if i have subclassed my bot, can i still do @bot.event?

slate swan
heavy folio
#

alr

#

but is it recommended? cuz i see some other bots doing everything just in the class

slate swan
#

yes

#

there's no problem in doing it that way

heavy folio
#

yes as in?

#

oh okay thanks

#

also just curious why some bots do py if __name__ == "__main__"": bot = MyBot() bot.run

#

and what it means

untold token
heavy folio
untold token
#

Normally when I subclass, I don't override the default on_message event, rather I just use event listeners

heavy folio
#

does it affect?

untold token
#

Bot.listen()

untold token
#

It's an external listener

heavy folio
#

alr then

untold token
#

So it will not affect

heavy folio
#

so i can have checks normally?

untold token
#

checks?

heavy folio
#

@bot.check

untold token
#

Hm yeah you can

heavy folio
#

kden thbanks

untold token
shadow wraith
#

crap i use 2.0

untold token
#

See

#

That's why

#

It is intended to work with dpy 1.7

shadow wraith
#

wait do you actually use discord_slash

untold token
#

I don't

shadow wraith
#

oh

untold token
#

I use disnake

shadow wraith
#

ok so i converted it back to a normal command (instead of slash) and i got this traceback

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/bot.py", line 227, in eliminate
    await member.remove_roles(919570782185750578)
  File "/home/container/.local/lib/python3.10/site-packages/discord/member.py", line 891, in remove_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'

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

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.10/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: AttributeError: 'int' object has no attribute 'id'
slate swan
#

the remove_roles takes a discord.Role not an int

shadow wraith
#

if it doesn't take an int, it prob doesn't take a str 💀

manic wing
#

no.

slate swan
#

it takes a discord.Role

manic wing
#

you can do role = guild.get_role(role_id)

shadow wraith
#

oh

manic wing
#

and pass role

shadow wraith
#

ok but you can still use guild.get_role in if statements?

slate swan
#

yes

shadow wraith
#

oh alright

stark lintel
#

can someone help me with a slash command issue?

maiden fable
#

Sure

stark lintel
#

@maiden fable here's the issue, you see how it shows up in my list as hello

#

it's name was changed in my code like 8 hours ago to results

#

why won't it update?

maiden fable
#

Discord/Lib Issue

stark lintel
#

is there a fix?

heavy folio
#
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            extension = filename[:-3]
            try:
                self.load_extension(f'cogs.{extension}')
                print(f"Successfully loaded extension \'{extension}\'")
            except Exception as e:
                exception = f"{type(e).__name__}: \'{e}\'"
                print(f"---------------------\nFailed to load extension \'{extension}\'\n-- {exception}")
```i've tried bringing this into the subclassed bot (`class MyBot(commands.Bot):`) and changed `bot.` to `self.` but it's now telling me self is not defined
maiden fable
stark lintel
#

damn that sucks

heavy folio
#
class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='.')
    
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            extension = filename[:-3]
            try:
                self.load_extension(f'cogs.{extension}')
                print(f"Successfully loaded extension \'{extension}\'")
            except Exception as e:
                exception = f"{type(e).__name__}: \'{e}\'"
                print(f"---------------------\nFailed to load extension \'{extension}\'\n-- {exception}")
boreal ravine
#

guys give command ideas

#

I'm desperately in need in some

stark lintel
boreal ravine
heavy folio
#

oh

boreal ravine
stark lintel
#

hmm

heavy folio
boreal ravine
stark lintel
#

ok, im gonna give it another day to try to fix itself

heavy folio
#

or a whatis command and how it works is you pass in a guild/user/channel/role id and it'll give info

boreal ravine
stark lintel
#

ok, ill try that

boreal ravine
late wigeon
#

how do i start an async thread when someone clicks a button, I'm trying to make something that handles multiple interactions with different people at once

heavy folio
#

would loading extensions in on_ready be a good idea (subclassed bot)

boreal ravine
stark lintel
#

@boreal ravine @maiden fable I found a fix, i needed to add sync_commands and sync_on_cog_reload

boreal ravine
#

o nice

stark lintel
heavy folio
#

alr then

boreal ravine
#

?

heavy folio
#
class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='.')
    
    def loadcogs(self):
        for filename in os.listdir('./cogs'):
            if filename.endswith('.py'):
                extension = filename[:-3]
                try:
                    self.load_extension(f'cogs.{extension}')
                    print(f"Successfully loaded extension \'{extension}\'")
                except Exception as e:
                    exception = f"{type(e).__name__}: \'{e}\'"
                    print(f"---------------------\nFailed to load extension \'{extension}\'\n-- {exception}")
stark lintel
#

here's another error though @boreal ravine When i try to get a response from my slash command, i get an error with the button

potent spear
jovial osprey
#

how can i make a command loop ? like i do a command with embed and after 10 seconds it deletes itself and then it runs again

heavy folio
#

idk i wanna do it all in the class if it's possible

#

but i guess it's fine then

stark lintel
#

here's the code

boreal ravine
#

It happens when you use 3rd party libs

slate swan
heavy folio
stark lintel
#

sure

slate swan
#

error too

stark lintel
#

sure

#

let me do that, give me one sec...

#

Here's the code:

@slash.slash(name="results", description="Brings up survey results. Must be `administrator` to run this command")
async def results(ctx: SlashContext):#disnake
    print("")
    print(f"Results command triggered {time.strftime('%H:%M:%S, %m-%d-%Y')}...")
    if ctx.author.guild_permissions.administrator:
        embed = discord.Embed(color = 0x800020)
        embed.title = "Survey Results:"
        embed.description = "Hello `Administrator`, please click on the button below to access the survey results!!"
        embed.timestamp=datetime.datetime.utcnow()
        embed.set_footer(text=f'AHSweather v{_version_} \u200b')
        #bcc = client.get_channel(886307415518240768)#general
        b1 = Button(style=ButtonStyle.URL, label = 'Go to the survey results!', url="https://www.surveyhero.com/user/surveys/657976/responses")
        #b2 = Button(style=ButtonStyle.grey, label = "I'm neutral")
        #b3 = Button(style=ButtonStyle.red, label = 'I did not like it')
        await ctx.send(embed=embed, components=[b1], hidden=True)

    else:
        await ctx.send(f"Sorry, you don't have the permissions to run this command! You are missing the following permissions: `administrator`", hidden=True)
heavy folio
#

dont use discord components (3rd party lib)

#

disnake has it's ui.Button

stark lintel
#
An exception has occurred while executing command `results`:
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\client.py", line 1352, in invoke_command
    await func.invoke(ctx, **args)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\model.py", line 210, in invoke
    return await self.func(*args, **kwargs)
  File "C:/Users/Administrator/AppData/Local/Programs/Python/Python310/AHSweather_bot_3.4.10.py", line 855, in results
    await ctx.send(embed=embed, components=[b1], hidden=True)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\context.py", line 215, in send
    if components and not all(comp.get("type") == 1 for comp in components):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\context.py", line 215, in <genexpr>
    if components and not all(comp.get("type") == 1 for comp in components):
AttributeError: 'Button' object has no attribute 'get'
heavy folio
#

use that and not components

jovial osprey
# potent spear concrete?

sending command that purges itself after 10 seconds and then like i sent it again but actually it was the command that sent itself

stark lintel
#

ok, im gonna switch to disnake

#

ill brb

potent spear
slate swan
#

'Button' object has no attribute 'get'

velvet tinsel
#

Which module are you using?

heavy folio
#

oops

slate swan
#

discord_slash

velvet tinsel
#

Oh

#

Idk never used it

heavy folio
boreal ravine
#

guys gimme command ideas

boreal ravine
slate swan
#

im not the one using discord_slash ;-;

manic wing
#

even they might be too dificult for you

slate swan
boreal ravine
slate swan
#

hangman?

manic wing
boreal ravine
#

never

boreal ravine
slate swan
#

hangman?

boreal ravine
slate swan
#

see not that difficult for him

boreal ravine
slate swan
#

even i have those in my bot

maiden fable
manic wing
#

kayle do you have a bot

boreal ravine
manic wing
boreal ravine
manic wing
boreal ravine
maiden fable
boreal ravine
maiden fable
manic wing
slate swan
#

me too

#

:D

boreal ravine
#

my bot isnt public, its only in my server right now

manic wing
#

can I join your server

slate swan
#

yeah i wanna join

boreal ravine
#

i mean sure

maiden fable
#

😶

slate swan
#

dm the invite :D

tawdry perch
#

what invite 👀

maiden fable
#

Private Server Invite

tawdry perch
#

bot server?

maiden fable
#

Mhm

tawdry perch
#

I want to yeet features to my bot, gib invite if you can

jovial osprey
#

how can i make command do another command ?

tawdry perch
#

oh now I remember what I had to do, fix my bot's constant files ...

maiden fable
unkempt canyonBOT
#

await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.
tawdry perch
#

I'm waiting the time when this embed gets paginated, but I broke my constants and the bot cant even run atm 🤦

#

it's a bit too long

maiden fable
#

Hmmmmmmm

#

Just use views

#

Tbh I love the implementation of ui.View

#

Not talking about Internals, but the end developer implementation

slate swan
#

trying to make a giveaway function

@bot.command()
async def test(ctx, time=None, *, prize=None):
    if time == None:
        return await ctx.send('time bata ')
    elif prize == None:
        return await ctx.send('abe prize kya hai?')
    embed = discord.Embed(title='hm', description=f'{prize}', color=0xcf244)
    embed.set_footer(text=f'ends in {time}')
    time_covert = {"s":1, "m":60, 'h':3600, 'd':86400}
    gaw_time = int(time[0]) * time_covert[time[-1]]
    gaw_msg = await ctx.send(embed=embed)
    await gaw_msg.add_reaction('🎉')
    await asyncio.sleep(gaw_time)

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

    users = await gaw_msg2.add_reaction[0].users().flatten()
    users.pop(users.index(bot.user))

    winner = random.choice(users)

    await ctx.send(f'{winner.mention} and won {prize}')```
error: 
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
jovial osprey
#

i used invoke on my command and after some time it did this Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message does anyone know why ?

small igloo
#

is there any API to make discord bot search google?

maiden fable
small igloo
maiden fable
#

!pypi google

unkempt canyonBOT
maiden fable
#

This, iirc

small igloo
#

ok, thanks :3

jovial osprey
slate swan
#

you tried to delete the authors message?

small igloo
maiden fable
#

Idk, seems like it

small igloo
#

ok, thanks

slate swan
#

replit bad

tawdry perch
#

this is how you assigned a help command to bot, right? ```py
bot.help_command = MyNewHelp()

jovial osprey
#

why are buttons working only once ?

#

is there a way to fix it ?

tawdry perch
#

what I guess is after interaction it has 1 task to do and when it's done it wont repeat it

slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
slate swan
#

This kwarg

tawdry perch
#

but the other one works as well, right?

slate swan
#

Yes

jovial osprey
#

i tried fixing the buttons with looping but it makes sounds and its just not working, any other ideas ?

tawdry perch
#

hm

#

how can I convert help output to list of embeds?

manic wing
#

dont know why you would want to do that

#

but idk what you mean

#

elaborate

boreal ravine
#

hm

shadow wraith
#

does discord.py 2.0 use "on_raw_reaction_add" or "on_reaction_add"

boreal ravine
#

@manic wing nice bot btw, 7.5/10 rating

shadow wraith
sage otter
#

on_raw works with shit that’s not in cache

shadow wraith
#

well my bot host uses caching and stuff so i will just use on_reaction_add

boreal ravine
#

pog

sage otter
#

pog

shadow wraith
#

not pog since idk how to use reactions in an on_message event 💀

sage otter
#

Use reactions in which way

small igloo
#

what is this

shadow wraith
#

udk python?

final iron
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

sage otter
#

Also you can’t have empty field values like that

small igloo
small igloo
sage otter
#

I mean you can if you use unicode chars

shadow wraith
#

yea

#

but im not sure if repl.it supports unicode chars 🤔

sage otter
#

But if you have an empty string that won’t work.

shadow wraith
#

ok but how else am i gonna specify reaction if i get an error and there's no obj 💀

sage otter
#

Use logic to check stuff first

#

And I thought you said this was in a on_message

#

There’s no ctx in on_message

manic wing
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.
small igloo
small igloo
trim meadow
#

Hello everyone. I am trying to make a welcome message when someone joins my server, but for some reason it doesn't work. Anyone got any ideas?

flat flower
#

done

small igloo
small igloo
trim meadow
small igloo
trim meadow
small igloo
trim meadow
small igloo
slate swan
#

How can I add one of those buttons like this

#

I wanna add a Refresh button

jovial osprey
tawdry perch
#

I alrd took a look at pinned messages

manic wing
#

oh so a paginator

#

you coulda said so

small igloo
tawdry perch
#

Would have made sense

small igloo
# slate swan

from my last experience (idk the others) the button no longer work... since InteractionType removed in discord.py

patent bluff
#

wia tno

#

wait what

small igloo
#

what?

small igloo
slate swan
small igloo
#

bhre no one knows why my error appear? and how to remove it

slate swan
cosmic forge
#

I'm new to making discord bots and i need some help with a problem im having dm me if you think you can help

small igloo
cosmic forge
small igloo
lost wolf
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'open_account' is not defined

#
import discord 
from discord.ext import commands
import json

class Economy(commands.Cog):
    def __init__(self, bot):
        self.bot = bot



    async def get_bank_data():
        with open("bank.json", 'r') as f:
             users = json.load(f)
        return users

    async def open_account(user):
        users = await get_bank_data()

        if str(user.id) in users:
                return False
        else:
            users[str(user.id)] = {}
            users[str(user.id)]["Wallet"] = 0
            users[str(user.id)]["Bank"] = 0

            with open("bank.json", "w") as f:
                json.dump(users, f)

            return True


    @commands.command()
    async def balance(self, ctx):
        await open_account(ctx.author)

        user = ctx.author

        users = await get_bank_data()

        wallet_amt = users[str(user.id)]["Wallet"]
        bank_amt = users[str(user.id)]["Bank"]

        em = discord.Embed(title=f"{ctx.author.name}'s Balance", color= discord.Color.teal)
        em.add_field(name="Wallet", value=wallet_amt)
        em.add_field(name="Bank", value=bank_amt)
        await ctx.send(embed=em)




def setup(bot):
    bot.add_cog(Economy(bot))
#

my economy cog

slate swan
jovial osprey
#

how can i add role to someone when someone presses a button ?

#

im using discord_components

slate swan
slate swan
#

btw seems like just a helper function to me

lost wolf
slate swan
#

and include self as the first arg in those functions

lost wolf
#

anyways

lost wolf
slate swan
boreal ravine
#

how can I shorten this code to one line ```py
m = ctx.guild.get_member(645582953434316802)
await m.send('hi')

lost wolf
#

i dont define it like that

slate swan
#

you are in a class

#
    await ctx.send(embed=embed, components=[
            [Button(style=ButtonStyle.URL, label="Refresh")]]
lost wolf
#

" await open_account(ctx.author)"

lost wolf
slate swan
#

ofcourse

lost wolf
#

mk

#

thanks

slate swan
#
        await ctx.send(embed=embed, components=[
            [Button(style=ButtonStyle.URL, label="Refresh")]])

C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Launch Successful!
Ignoring exception in command ping:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 26, in pingme
[Button(style=ButtonStyle.URL, label="Refresh")]])
NameError: name 'Button' is not defined

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

Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\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 'Button' is not defined

slate swan
#

how else do you want to use it?

slate swan
#

what import is it? import button?

patent bluff
#

then why r u using it...

slate swan
patent bluff
#

u haven't even imported it

slate swan
#

nvm figured it out

slate swan
slate swan
#

yw

lost wolf
small igloo
#

blah i still struggle with my error ;-; someone pls helpp

slate swan
#

C:\Users\ADMIN\PycharmProjects\Fluxo>python main.py
Launch Successful!
Ignoring exception in command ping:
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ADMIN\PycharmProjects\Fluxo\main.py", line 28, in pingme
[Button(emoji=self.bot.get_emoji(919616911782871061), style=ButtonStyle.grey, label="Refresh")]])
NameError: name 'self' is not defined

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

Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ADMIN\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\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 'self' is not defined

#
        await ctx.send(embed=embed, components=[
            [Button(emoji=self.bot.get_emoji(919616911782871061), style=ButtonStyle.grey, label="Refresh")]])
patent bluff
#

send the whole function

rigid torrent
#

`import discord
from discord.ext import commands
import os
token = os.environ['TOKEN']

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

@client.command()
@commands.is_owner()
async def say(ctx, *, message):
await ctx.message.delete()
await ctx.send(message)
client.run(token,bot=True)`

#

Why not working

slate swan
#

error?.......

rigid torrent
#

No

#

But it's not replying

slate swan
#

does it even start? , and what's not working

patent bluff
rigid torrent
slate swan
#

nop

slate swan
slate swan
rigid torrent
slate swan
#

so do i just remove self?

small igloo
#

help my error ;-;

slate swan
#

yea it fixes your error

slate swan
#

oof does animated emojis not work for buttons?

slate swan
small igloo
rigid torrent
small igloo
#

:l ....

rigid torrent
#

All are working but it's not replying

slate swan
small igloo
slate swan
#

no

#

!indents

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

small igloo
#

nah, where is the problem in my code?

slate swan
#

i mean , the error says it all

small igloo
#

sup @upbeat otter

lost wolf
#
  File "/home/allans/Bot/main.py", line 11, in <module>
    client = commands.Bot(command_prefix=">", help_command = PrettyHelp, intents = intents)
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 127, in __init__
    self.help_command = help_command
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 799, in help_command
    raise TypeError('help_command must be a subclass of HelpCommand')
TypeError: help_command must be a subclass of HelpCommand
upbeat otter
small igloo
lost wolf
#

???

upbeat otter
small igloo
slate swan
quick gust
upbeat otter
rigid torrent
#

Sed on one helping xD

upbeat otter
slate swan
rigid torrent
# upbeat otter askk

`import discord
from discord.ext import commands
import os
token = os.environ['TOKEN']

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

@client.command()
@commands.is_owner()
async def say(ctx, *, message):
await ctx.message.delete()
await ctx.send(message)
client.run(token,bot=True)`

small igloo
lost wolf
small igloo
slate swan
#
        await ctx.send(embed=embed, components=[
            [Button(style=ButtonStyle.grey, label="Refresh", emoji=bot.get_emoji(919622656049967164))]])

shows this:

rigid torrent
slate swan
upbeat otter
rigid torrent
#

All ok but idk why it's not replying

quick gust
#

not (message)

upbeat otter
quick gust
#

or typehint it to a str in the arg

#

doesn't?

upbeat otter
quick gust
#

Oh I see

upbeat otter
#

ye

quick gust
#

They have @is_owner, but who is the owner lmao?

lost wolf
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: get_bank_data() takes 0 positional arguments but 1 was given
slate swan
slate swan
lost wolf
#
import discord 
from discord.ext import commands
import json

class Economy(commands.Cog):
    def __init__(self, bot):
        self.bot = bot



    async def get_bank_data():
        with open("bank.json", 'r') as f:
             users = json.load(f)
        return users

    async def open_account(self, user):
        users = await self.get_bank_data()

        if str(user.id) in users:
                return False
        else:
            users[str(user.id)] = {}
            users[str(user.id)]["Wallet"] = 0
            users[str(user.id)]["Bank"] = 0

            with open("bank.json", "w") as f:
                json.dump(users, f)

            return True


    @commands.command()
    async def balance(self, ctx):
        await self.open_account(ctx.author)

        user = ctx.author

        users = await self.get_bank_data()

        wallet_amt = users[str(user.id)]["Wallet"]
        bank_amt = users[str(user.id)]["Bank"]

        em = discord.Embed(title=f"{ctx.author.name}'s Balance", color= discord.Color.teal)
        em.add_field(name="Wallet", value=wallet_amt)
        em.add_field(name="Bank", value=bank_amt)
        await ctx.send(embed=em)




def setup(bot):
    bot.add_cog(Economy(bot))
upbeat otter
quick gust
#

yes...

slate swan
lost wolf
#

async def self.get_bank_data()?

small igloo
slate swan
quick gust
upbeat otter
quick gust
#

unless I'm missing something

small igloo
#

what time r there btw

upbeat otter
slate swan
#

and it wont be commands.is_owner() ofc

quick gust
#

have they even made an is_owner function?

slate swan
#

nu

quick gust
#

then how does the bot know what is_owner is, they haven't even imported it and it should raise an error

hollow steeple
#

iirc is_owner errors if owner_id or owner_ids is not set

quick gust
final iron
#

!d discord.ext.commands.is_owner

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
upbeat otter
quick gust
slate swan
small igloo
#

still doesnt have any idea how to resolve my error :l

boreal ravine
tawdry perch
#

how can I create a embed paginator? I alrd tried to read the examples from the pinned messages

quick gust
small igloo
final iron
tawdry perch
#

that's eh.. confusing

boreal ravine
#

yes

boreal ravine
small igloo
boreal ravine
#

if you dont understand it just ask here lol

tawdry perch
#

is there a way to convert the help output to list of embeds?

#

if yes, then it will be easy to paginate the help embed

bitter perch
tawdry perch
#

help command output*

bitter perch
#

Try don't newline function definitions, the fuck

boreal ravine
boreal ravine
tawdry perch
#

never even hear that term "spacing"

boreal ravine
#

he means newlines

tawdry perch
#

oh

bitter perch
#

That file is incredibly hard to look at

#

There is not a single newline

tawdry perch
#

but ye, the current embed is a bit too large, I alrd have a embed paginator but I don't yet know how to convert it to list of embeds (the help embed)

bitter perch
#

To organize code

hollow steeple
#

It doesn't follow any of the standard code conventions for python, but if it works then it works

tawdry perch
# boreal ravine is this `send_page_help`?

it's this ```py
class MyNewHelp(commands.MinimalHelpCommand):
async def send_pages(self):

    destination = self.get_destination()
    for page in self.paginator.pages:
        emby = disnake.Embed(description=page)
        await destination.send(embed=emby)

bot.help_command = MyNewHelp()

boreal ravine
#

hm

tawdry perch
#

I made that (or copied most likely) about 6 months ago so I have not touched it after that

#

changed discord to disnake tho

boreal ravine
tawdry perch
#

oh..

boreal ravine
#

you'd need to use another method, send_bot_help I think

tawdry perch
#

instead of send_pages?

boreal ravine
boreal ravine
tawdry perch
boreal ravine
#

yes

tawdry perch
boreal ravine
#

hm

tawdry perch
#

I think it wont work if I just yeet the code (which I did)

boreal ravine
#

it's very basic

#

you should understand whats going on the code

tawdry perch
#

there is a change i some how understand what it does but there is no way I know how to use that

boreal ravine
tawdry perch
#

and which one of those would be for help command?

shadow wraith
#

what things can you do with interaction.response other than send_message

#

because i wanna add more stuff to my discord buttons :P

boreal ravine
shadow wraith
#

!d discord.Interaction.response

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

boreal ravine
tawdry perch
#

so I still need to convert the help command thing to list?

boreal ravine
#

!d discord.Interaction.edit_original_message @shadow wraith?

unkempt canyonBOT
#

await edit_original_message(*, content=..., embeds=..., embed=..., file=..., files=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
shadow wraith
#

🤔

slate swan
#

how do i edit an embed lmao

#

oh

boreal ravine
unkempt canyonBOT
#

await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
shadow wraith
boreal ravine
#

get another embed object and get the message object, edit it using the embed kwarg

slate swan
#

yeah ik , i'm not illiterate

boreal ravine
boreal ravine
tawdry perch
#

why does this not print anything? ```py
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self, ctx):
destination = self.get_destination()
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
embeds.append(emby)
await destination.send('test', view=EmbedPaginator(ctx, embeds, timeout=180))

lost wolf
#

is sharding possible with python?

#

if so is there a doc on it?

tawdry perch
#

oh

lethal moat
#
class OpenTicketButton(nextcord.ui.View):
    def __init__(self, ctx: commands.Context) -> None:
        self.ctx = ctx
        super().__init__(timeout=None)
        self.value = None

    @nextcord.ui.button(label="Create a Ticket", style=nextcord.ButtonStyle.green)
    async def createticket(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        ctx = interaction.user
        await TicketOptions(ctx)
async def TicketOptions(ctx):
    view = TicketOptionsClass(ctx)
    embed = nextcord.Embed(title="Support", description="Please pick a ticket category from the dropdown below to finish creating your ticket.")
    await ctx.author.send(embed=embed, view=view)
    await view.wait()

    if view.value == None:
        await ctx.author.send("You took too long to choose! try again later.")
    
    else:
        issue = view.value
        await MakeATicket(ctx, issue)

'Member' object has no attribute 'author'

boreal ravine
#

hm

lost wolf
#

is sharding possible with python?
if so is there a doc on it?

boreal ravine
lethal moat
#
class TicketOptionsClass(nextcord.ui.View):
    def __init__(self, ctx: commands.Context) -> None:
        self.ctx = ctx
        super().__init__(timeout=120)
        self.value = None

    @nextcord.ui.button(label="General", style=nextcord.ButtonStyle.blurple)
    async def generalissues(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
        else:
            self.value = "General Issues"
            self.stop()

    @nextcord.ui.button(label="Factions", style=nextcord.ButtonStyle.blurple)
    async def factionsissues(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
        else:
            self.value = "Factions Issues"
            self.stop()

    @nextcord.ui.button(label="Buycraft", style=nextcord.ButtonStyle.blurple)
    async def buycraftissues(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
        else:
            self.value = "Buycraft Issues"
            self.stop()

    @nextcord.ui.button(label="Player Reports", style=nextcord.ButtonStyle.blurple)
    async def playerreport(self, button:nextcord.ui.Button, interaction: nextcord.Interaction):
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message(f"Sorry but this button isn't for you! {interaction.user.mention}", ephemeral=True)
        else:
            self.value = "Player Reports"
            self.stop()
tawdry perch
#
class MyNewHelp(commands.MinimalHelpCommand):
    async def send_bot_help(self, ctx):
        destination = self.get_destination()
        embeds = []
        print(embeds)
        for page in self.paginator.pages:
            emby = disnake.Embed(description=page)
            print(emby)
            print(embeds)
            print("Is this even ran?")
            embeds.append(emby)
        print(embeds)
        await destination.send('test', view=EmbedPaginator(ctx, embeds, timeout=180))
``` I added a few more print, and nothin
#

isn't this supposed to be called on every !help command?

lethal moat
boreal ravine
lethal moat
#

probably because of this

        ctx = interaction.user
        await TicketOptions(ctx)
boreal ravine
#

probably lmfao

lethal moat
#

is there a way i can fix that

boreal ravine
#

just use self.ctx in the argument (ticketoptions class where you call it)

lethal moat
#

i am trying to make an open ticket button, that wont work

boreal ravine
#

you can make the class have extra arguments though

lethal moat
#

it will just use the ctx value for the person who ran the command to get the embed with the button up

lost wolf
#

is sharding possible with python yet?

slate swan
#

!d discord.ext.commands.AutoShardedBot

unkempt canyonBOT
#

class discord.ext.commands.AutoShardedBot(command_prefix, help_command=<default-help-command>, description=None, **options)```
This is similar to [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") except that it is inherited from [`discord.AutoShardedClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.AutoShardedClient "discord.AutoShardedClient") instead.
slate swan
#

it always was

#

hey i am trying to make a bot.wait_for
the command is working good its just an error is coming
codes:

@bot.listen()
async def on_message(message):
    if message.content.startswith('s!satan'):
        channel = message.channel
        embed = discord.Embed(title="WARNING:", description="**After Reading Anyone Of These Doujins,You May Ask Yourself Question such as\nWhy?,What I Just Read?,Am I Okay?,etc\n(Hand Picked By Creator-sama)**")
        embed.set_footer(text='Type CONFIRM To Read')
        await channel.send(embed=embed)

    def check(m):
        return m.content == 'CONFIRM' and m.channel == channel

    with open('satan.txt', 'r') as f:
        lines = f.readlines()
        g = random.choice(lines)

    msg = await bot.wait_for('message', check=check)
    await message.channel.send(g.format(msg))```
error: 
    return m.content == 'CONFIRM' and m.channel == channel
NameError: free variable 'channel' referenced before assignment in enclosing scope
tawdry perch
slate swan
tawdry perch
#

No I added the help command a different way, let me find it

slate swan
tawdry perch
#
bot.help_command = MyNewHelp()
slate swan
tawdry perch
#

I don't think that's a good way

#

but shouldn't that class be called everytime I type !help

winter geyser
slate swan
#
RuntimeError: Concurrent call to receive() is not allowed
#

what does this error mean? I'd send the code but it doesn't say what's causing the error

slate swan
#

i tried to help as possible

slate swan
tawdry perch
#

hmm why does it not print anything then?

slate swan
#

do someone know whats dis called?

devout iris
#

how can i make an eval commad??

maiden fable
#

!d exec

unkempt canyonBOT
#

exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
maiden fable
#

!d eval

unkempt canyonBOT
#

eval(expression[, globals[, locals]])```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.
maiden fable
#

@devout iris

slate swan
maiden fable
#

!d discord.ButtonStyle.link

unkempt canyonBOT
maiden fable
#

This?

velvet tinsel
velvet tinsel
#

It won’t work

#

For a discord bot

#

You have to do something like stdout or whatever tylerr said

#

It will only print the evaluated code, but when sending the result it returns None

manic wing
# devout iris how can i make an eval commad??

Welcome back to the discord.py series! Here's a overwhelmingly requested command :D

Read description for links!

----------------------------------------­­---------------------------------------­-­--

Need Help?
Require help with your code? Why not head on over to our dedicated support discord where you can receive only the best support: https:...

▶ Play video
velvet tinsel
#

Thanks Caeden, I needed that as well

maiden fable
#

Me who made an eval without any tutorial: 😐

velvet tinsel
tawdry perch
velvet tinsel
#

Sweet, you used eval()?

#

Why did you do embeds.append?

#

Does that actually work?

#

@tawdry perch

tawdry perch
#

It was supposed to create list of embeds

velvet tinsel
#

Ah~

tawdry perch
#

In theory it could work

velvet tinsel
#

I thought embeds was an embed

#

My bad

tawdry perch
#

Ah no

velvet tinsel
#

?

#

What did it print?

tawdry perch
#

Nothing

velvet tinsel
#

Oh

tawdry perch
#

Not even the text

velvet tinsel
#

Try doing help_command=None

#

Or whatever it is

upbeat otter
lost wolf
#

@hollow quarry is sharding possible in dpy yet?

velvet tinsel
#

greetings Eevee

upbeat otter
velvet tinsel
#

yert stop being so sus

lost wolf
upbeat otter
hollow quarry
lost wolf
pliant gulch
#

It isn't actually context

upbeat otter
velvet tinsel
upbeat otter
pliant gulch
tawdry perch
#

Oh...

#

Can I get the context obj?

pliant gulch
#

Read the note

tawdry perch
#

Oo, let me try that in a while

velvet tinsel
upbeat otter
#

smh

slate swan
#

Hello

tawdry perch
slate swan
#
@commands.has_permissions(manage_messages = True)
async def purge(ctx, amount=2):
    await ctx.channel.purge(limit=amount)```
#

members without perms can purge.Why?

tawdry perch
#

oh

pliant gulch
#

HelpCommand is the class, you want the instance

#

Since your subclassing it, you have a HelpCommand instance inside of self

upbeat otter
tawdry perch
#

so I have to do self.context?

upbeat otter
#

anyways, best of luck

slate swan
#

can someone answer it

#

why is that happening

pliant gulch
tawdry perch
#

oh

#

now I have this, but nothing is being printed ```py
class MyNewHelp(commands.MinimalHelpCommand):
async def send_bot_help(self):
destination = self.get_destination()
embeds = []
print(embeds)
for page in self.paginator.pages:
emby = disnake.Embed(description=page)
print(emby)
print(embeds)
print("Is this even ran?")
embeds.append(emby)
print(embeds)
await destination.send('test', view=EmbedPaginator(self.context, embeds, timeout=180))
bot.help_command = MyNewHelp()

pliant gulch
#

Probably because it's erroring

#

Did you read the docs page I sent???

pliant gulch
#

It takes 1 arg

tawdry perch
#

which is mapping?

pliant gulch
#

Yes,

tawdry perch
#

and what does that mean?

pliant gulch
#

And in the snippet you just sent you only have self

slate swan
#

anyone answer my problem pls

pliant gulch
#

Where is the another argument this method takes???

tawdry perch
#

uh nowhere

pliant gulch
#

Exactly

#

!e ```py
def foo(a): ...
foo(1, 2)

unkempt canyonBOT
#

@pliant gulch :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: foo() takes 1 positional argument but 2 were given
tawdry perch
#

I see, but what is mapping? Like what do I need to do with it

pliant gulch
#

Mapping is a list of your bot's commands

#

You can do whatever withit

#

For mine I used it to format my help embed

tawdry perch
#

hmm so if I just pass it to the help command but I don't use it, it should be ok?

pliant gulch
#

Just pass it to the send_bot_help method

#

You don't need to use it

tawdry perch
#

still nothing in console

pliant gulch
#

The prints don't showup?

tawdry perch
#
class MyNewHelp(commands.MinimalHelpCommand):
    async def send_bot_help(self, mapping):
        destination = self.get_destination()
        print(mapping)
        embeds = []
        print(embeds)
        for page in self.paginator.pages:
            emby = disnake.Embed(description=page)
            print(emby)
            print(embeds)
            print("Is this even ran?")
            embeds.append(emby)
        print(embeds)
        await destination.send('test', view=EmbedPaginator(self.context, embeds, timeout=180))
``` this is what I currently have
#

it prints nothing

pliant gulch
#

You probably are erroring somewhere else as well then ¯_(ツ)_/¯

#

Or it's stalling somewhere

tawdry perch
#

there are no tracebacks anywhere

#

it sends this embed always, but nothing else

sage locust
#

Hey does anyone know of a surefire way to check message contents for exploits/attempted code injections/abuse. Basically a generic reliable message sanitizer

tawdry perch
devout iris
#

smh, what is wrong?

manic wing
#
@commands.command()
    async def uptime(self, ctx:Context):

        delta_uptime = datetime.utcnow() - self.bot.launch_time
        hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)
        return await thebed(ctx, '', f"I've been Up since **{days}** Days, **{hours}** Hours, **{minutes}** Minutes, and **{seconds}** Seconds!")


devout iris
#

i'm not using classes :/

proven osprey
#

guys anybody now why does it can't recognize "message"? maybe i need to import something?

tawdry perch
proven osprey
#

thats all i got

devout iris
quick gust
tawdry perch
#

just remove self from vars and use bot commands structure

quick gust
#

pass the message kwarg

proven osprey
quick gust
#

no

proven osprey
quick gust
#

u have to define users

proven osprey
#

now i have another problem)

tawdry perch
#

indent?

devout iris
tawdry perch
#

did you just copy paste it..

quick gust
tawdry perch
#

oh my bad

devout iris
tawdry perch
#

such as?

#

oh those yellow lined things

#

you can remove typehint from ctx, or do ctx: commands.Context (iirc)

#

and thebed seems to be a custom function so use normal ctx.send

quick gust
tawdry perch
#

what?

quick gust
#

why did you say that? I thought u misunderstood what I said

tawdry perch
#

eh forget it, I can't even try explaining it

quick gust
#

okay

slate swan
#
@commands.has_permissions(manage_messages=True)
async def purge(ctx , amount=2):
    await ctx.channel.purge(limit=amount)```

members without perms can purge msges pls tell how to fix thi
#

@quick gust

tawdry perch
#

show your code, can you?

devout iris
#

yep a sec

devout iris
final iron
#

It should be working fine

slate swan
tawdry perch
devout iris
final iron
devout iris
devout iris
tawdry perch
#

that is for cogs afaik

devout iris
#

ah

#

i wasn't use cogs anytime so i wasnt know thx

tawdry perch
#

also, remove ctx from ctx.send("") remove ctx from inside ()

quick gust
devout iris
#

here?

tawdry perch
#

remoce ctx, from inside it, also the empty ''

devout iris
#

alr

#

now okay?

tawdry perch
#

seems better

slate swan
#

@final iron is something wrong with my code?

devout iris
#

i'm gonna try now

final iron
slate swan
final iron
#

I have no idea

devout iris
#

eh

slate swan
final iron
tawdry perch
#

from datetime import datetime

#

Or that

final iron
#

I think their naming was a bad idea

#

With datetime being the module and datetime also being a class

quick gust
#

yeah it's wack

devout iris
devout iris
final iron
#

Yes

#

Im now wondering if you import datetime from datetime what happens if you're trying to access a class from the module and not a function from the datetime class

devout iris
#

stilll same

final iron
#

You didn't reload your bot

devout iris
#

already reloaded

final iron
#

The error is showing code thats not there

devout iris
#

hmm

#

i'll reload it again

#

not working....

final iron
#

Strange

#

Send the error again

devout iris
final iron
#

Is that from another place in your code?

devout iris
#

a sec

#

i have x2 uptime command but

#

"""one in it"""

final iron
#

No need to type hint ctx as commands.Context

#

You can just write ctx

devout iris
#

k

stiff nexus
#

how to know whats a cmds cooldown?

shadow wraith
devout iris
#

but sitll same

final iron
devout iris
final iron
#

Its redundant code

shadow wraith
#

not gonna argue over this but no need to spot-light that

shadow wraith
manic wing
unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
devout iris
shadow wraith
#

💀

slate swan
#

how can i seperate the values? im trying to put them into objects like bot.get_guild() bot.get_channel() and bot.get_role()

manic wing
devout iris
stiff nexus
#

not that

devout iris
manic wing
# devout iris

from datetime import datetime instead of import datetime

shadow wraith
#

:skul:

devout iris
shadow wraith
devout iris
manic wing
# devout iris ehh

when you do bot = commands.Bot(…) you need to also do bot.launch_time = datetime.utcnow()

#

copy and pasting code isn’t the best

devout iris
slate swan
manic wing
# devout iris

yes and after that you do bot.launch_time = datetime.utcnow()

devout iris
manic wing
#

not in the command

devout iris
#

ahh smhh

manic wing
#

Learn Python ❎ Go slowly ❎ Copy and Paste ✅ Ask questions and not understand the answer ✅

devout iris
manic wing
#

yes.

devout iris
#

cus i know basic python i guess 😄 (except OOP and a few funcs)

manic wing
#

ok thats a good start at least

devout iris
#

still same btw

manic wing
#

did you save it and restart?

manic wing
devout iris
slate swan
#

how can i seperate the values? im trying to put them into objects like bot.get_guild() bot.get_channel() and bot.get_role()

shadow wraith
#

i swear bot.launch_time is a thing how is it not working or you

slate swan
#

i might have mistyped

shadow wraith
#

:troll:

manic wing
#

it isnt a thing.

shadow wraith
manic wing
#

he hasnt saved it

#

its not a fucking this dude accept it

devout iris
#

okay i'll shutdown my bot fully and i'll restart from 0

#

u can see

manic wing
# devout iris

this adds the attribute launch_time to bot. so when you access bot it would have the attribute launch_time

#

youve just fucked something up

devout iris
manic wing
#

etc

devout iris
devout iris
manic wing
# devout iris lmao

ok remove from datetime import datetime and do - datetime.datetime.utcnow()

devout iris
#

like old?

manic wing
#

yes youve changed something

#

you keep changing shit

#

remove from datetime import datetime

devout iris
#

btw i wasn't change this func when i add new veriable

devout iris
#

did u understand me or not?

manic wing
#

no i dont understand at all

shadow wraith
#

most ineffecient code ever?

@bot.command()
async def eliminate(ctx, member: discord.Member):
    guild = member.guild
    SSCompetitor_Role = guild.get_role(919570782185750578)
    if ctx.channel.id == 919563757204693103:
        if guild.get_role(919571300467474543) in ctx.author.roles:
            if guild.get_role(919570782185750578) in member.roles:
                await member.remove_roles(SSCompetitor_Role)
                await ctx.send("{0} was eliminated! R.I.P".format(member.name))
    else:
        await ctx.message.delete()
devout iris
manic wing
#

is this all happening in one file?

#

send the file

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

Naming conventions NotLikeThis

devout iris
#

me?

manic wing
#

yes

devout iris
#

there is a lot of things in this file wait a bit

unkempt canyonBOT
devout iris
#

ah lol right

manic wing
#

ok dont do anything i dont tell you to do. change bot.launch_command = datetime.utcnow() to bot.launch_command = datetime.datetime.utcnow()

#

after you do this save, turn the bot off and restart.

manic wing
#

ok.

devout iris
#

yeesssss

devout iris
#

fiinally

manic wing
#

np.

slate swan
#
    @commands.Cog.listener()
    async def on_member_join(self, member):
        await self.update_totals(member)
        await self.bot.db.commit()
        inviter = await self.tracker.fetch_inviter(member)
        await self.bot.invites.upsert({"_id": inviter.id, "joiner_id": member.id})```
AttributeError: 'Bot' object has no attribute 'invites'
manic wing
manic wing
slate swan
#

so can you help?

slate swan
# manic wing `guild = bot.get_guild(configured[0][0])`, `get_channel(configured[0][1])`
    @commands.command()
    async def verc(self, ctx):
        configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall()
        guild = self.bot.get_guild(configured[0][0])
        channel = self.bot.get_channel(configured[0][1])
        role = self.bot.get_channel(configured[0][2])
        await ctx.send(configured)
        await ctx.send(f'{guild} {channel} {role}')```
edgy lion
#
    @commands.Cog.listener()
    async def on_guild_channel_update(self, before, after):
        async with aiohttp.ClientSession() as session:
            async with self.db.execute(
                    f"SELECT webhook, guild_id from 'logging' where guild_id = {before.guild.id}",
            ) as cursor:
                config = await cursor.fetchone()

            if config is not None:
                webhook = Webhook.from_url(config[0], adapter=AsyncWebhookAdapter(session))
                if before.guild.id == int(config[1]):
                    async for entry in before.guild.audit_logs(action=discord.AuditLogAction.channel_update,
                                                               oldest_first=False):
                        embed = discord.Embed(
                            description=f'Channel was updated ({after.mention})',
                            color=discord.Color.dark_theme()
                        )
                        embed.set_author(name=entry.user, icon_url=entry.user.avatar_url)
                        embed.timestamp = datetime.datetime.utcnow()
                        embed.set_footer(text=f'{self.bot.user}', icon_url=self.bot.user.avatar_url)
                        embed.add_field(name='Creation date', value=f'<t:{round(before.created_at.timestamp())}:D>',
                                        inline=False)

                        if before.overwrites:
                            embed.add_field(name='Overwrite deleted',
                                            value=f'For: role Undefined',
                                            inline=False)
                        if after.overwrites:
                            embed.add_field(name='Overwrite created',
                                            value=f'For: role Undefined',
                                            inline=False)``` why is the field not added although I add a role to a channel
manic wing
slate swan
#

@manic wing so can you help me?

#

role = self.bot.get_role(configured[0][2])

#

oh ctx.guild

patent lark
#

the bot object does not have a get_role method.

slate swan
#
    @commands.command()
    async def verc(self, ctx):
        configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall()
        guild = self.bot.get_guild(configured[0][0])
        channel = self.bot.get_channel(configured[0][1])
        role = ctx.guild.get_role(configured[0][2])
        await ctx.send(configured)
        await ctx.send(f'{guild} {channel} {role}')```
manic wing
manic wing
magic ore
manic wing
#

you're a genius man 🙇

somber parrot
#

lmao

magic ore
#

You should generally be storing them in the database as (big)ints as well

slate swan
#

oh wait

manic wing
#

i was on mobile

#

it needs to be int

somber parrot
#

stahp changing everything to strings

slate swan
#

ok i updated to py @commands.command() async def verc(self, ctx): configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall() guild = self.bot.get_guild(configured[0][0]) role = ctx.guild.get_role(configured[0][1]) channel = self.bot.get_channel(configured[0][2]) await ctx.send(configured) await ctx.send(f'{guild} {channel} {role}')

manic wing
#

no

#

you didnt change anything

slate swan
#

same output

somber parrot
#

STR

#

DO YOU KNOW WHAT AN STR IS

slate swan
manic wing
#

we said INT

somber parrot
#

INTTTTTTTTTTTTTTTT

slate swan
#

so (int(ctx.guild.id) for examlpe?

manic wing
#

int(configured[0][0])

slate swan
#

ohhi sse

manic wing
#

jeeeeeeezus

somber parrot
#

int everything

slate swan
#

The field in the database is a TEXT field

#

It doesn't matter how you insert it

#

It will always be returned as string.

#

So instead of acting like that you could tell that person to use BIGINT in the database structure

#

inviter = await self.tracker.fetch_inviter(member) await self.bot.invites.upsert({"_id": inviter.id, "joiner_id": member.id})
AttributeError: 'Bot' object has no attribute 'invites'

#

well now it returns the names

#

Instead of acting childish and almost insulting them..

somber parrot
#

Thats because I'm NOT 10

slate swan
#

I wouldn't joke about being 10 years old

somber parrot
#

Fine. 14

slate swan
#

this is for a verification configuration, how can i use that to get a guild, channel and role

slate swan
patent lark
slate swan
patent lark
#

too late

devout iris
#

@manic wingbro do u know how can i make an if condition for "if minutes == 0 or if hours == 0 .... bot won't show it in answer"

patent lark
#

XD

somber parrot
#

lol

slate swan
devout iris
#

like that

slate swan
#

inviter = await self.tracker.fetch_inviter(member) await self.bot.invites.upsert({"_id": inviter.id, "joiner_id": member.id})
AttributeError: 'Bot' object has no attribute 'invites'

manic wing
slate swan
#

If you copy code from GitHub or somewhere else, then copy it in its entirety at least..

manic wing
#

he said his friend wrote it for him

edgy lion
#
    @commands.Cog.listener()
    async def on_guild_channel_update(self, before, after):
        async with aiohttp.ClientSession() as session:
            async with self.db.execute(
                    f"SELECT webhook, guild_id from 'logging' where guild_id = {before.guild.id}",
            ) as cursor:
                config = await cursor.fetchone()

            if config is not None:
                webhook = Webhook.from_url(config[0], adapter=AsyncWebhookAdapter(session))
                if before.guild.id == int(config[1]):
                    async for entry in before.guild.audit_logs(action=discord.AuditLogAction.channel_update,
                                                               oldest_first=False):
                        embed = discord.Embed(
                            description=f'Channel was updated ({after.mention})',
                            color=discord.Color.dark_theme()
                        )
                        embed.set_author(name=entry.user, icon_url=entry.user.avatar_url)
                        embed.timestamp = datetime.datetime.utcnow()
                        embed.set_footer(text=f'{self.bot.user}', icon_url=self.bot.user.avatar_url)
                        embed.add_field(name='Creation date', value=f'<t:{round(before.created_at.timestamp())}:D>',
                                        inline=False)

                        if before.overwrites:
                            embed.add_field(name='Overwrite deleted',
                                            value=f'For: role Undefined',
                                            inline=False)
                        if after.overwrites:
                            embed.add_field(name='Overwrite created',
                                            value=f'For: role Undefined',
                                            inline=False)
                        await webhook.send(emebd=embed)``` why is the field not added although I add a role to a channel
slate swan
#

Then talk with your friend about it.

slate swan
slate swan
#

i can give u the pastebin link if you canm help

manic wing
slate swan
manic wing
#

can you not just send it here?

slate swan
#

okay

manic wing
#

if you just wanted to have it work in pycord, probably just replace every single word discord with pycord

#

through your ide

#

just mass replace all

#

yes...

#

just every single occurance

slate swan
#

here

#

https://oml.wtf/QvHFjbDJ

    embed = discord.Embed(title=f'Verification', description=f'You have `1` attempt to verify. If you fail, you may be re-evaluated by executing the command again', color=clr) 
IndentationError: unexpected indent```
#

weird

magic ore
#

Doesn't seem like they did from a quick glance at the GitHub

manic wing
#

whats the import? never used pycord lol

manic wing
slate swan
#

thats 1 tab (4 spaces)

manic wing
#

oh true

slate swan
#

¯_(ツ)_/¯

#

have you seen why @manic wing ?

dire folio
#

how do i delete a message with its id

manic wing
slate swan
dire folio
#

nvm

#

i got it

manic wing
tawdry perch
#
class MyNewHelp(commands.MinimalHelpCommand):
    async def send_bot_help(self, mapping):
        destination = self.get_destination()
        print(mapping)
        embeds = []
        print(embeds)
        for page in self.paginator.pages:
            emby = disnake.Embed(description=page)
            print(emby)
            print(embeds)
            print("Is this even ran?")
            embeds.append(emby)
        print(embeds)
        await destination.send('test', view=EmbedPaginator(self.context, embeds, timeout=180))
``` this is what I currently have, but it does not print anything/paginate the embed, why?
acoustic wind
#

Hey there, I changed my d.py bot to work with multiprocessing but every time I execute a command it stops after giving the final output... Does anyone know about that issue?

abstract kindle
#

is ctx.send_message a thing anymore?

#

I'm trying to dm a specific person whenever a command is run..

patent lark
#

just grab the user, using a member object. then use member.send()

#

!d discord.Member.send

unkempt canyonBOT
#

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
patent lark
#

no, its not a thing @abstract kindle

abstract kindle
#

yeah says ctx has no attribute member

patent lark
#

show me your code.

abstract kindle
#

so how would I send a message to a specific person? I know how to send a DM to the author of the previous message using ctx.author.send

#
username = await self.bot.wait_for(event="message", timeout=30.0)
                    owner = self.bot.get_user(326903703422500866)
                    await ctx.Member.send(owner, username)
patent lark
#

bot.get_user() returns the discord.User object not the discord.Member object

#

it would be await owner.send()

abstract kindle
#

i see

#

cool

#

that worked thank you very much

patent lark
#

no problem.

slate swan
#
    @commands.command()
    async def verify(self, ctx):
        member = ctx.author
        def check(m):
            return m.author == ctx.author

        configured = var.execute("SELECT * FROM verification WHERE guildid = ?", (str(ctx.guild.id), )).fetchall()
        vguild = self.bot.get_guild(int(configured[0][0]))
        vrole = ctx.guild.get_role(int(configured[0][1]))
        vchannel = self.bot.get_channel(int(configured[0][2]))

        if ctx.guild.id == vguild.id:
            if ctx.channel == vchannel.id:
                role = ctx.guild.get_role(vrole.id)
                ctx.message.delete()
#more code
        if role in member.roles: #UnboundLocalError: local variable 'role' referenced before assignment 
            alr = discord.Embed(title='Verification', description=f'You are already verified!', color=0x2f3136)
            await ctx.send(embed=alr, delete_after=5)
            return``` error is on the line it errors on
patent lark
#

your role variable is inside an if condition; if ctx.channel == vchannel.id:. so the role variable can only be used if this if condition returns a Truethy value. your if role in member.roles: statement will be invalid because then role is undefined.

slate swan