#discord-bots

1 messages · Page 909 of 1

sick birch
#

Invites are more associated with a channel

#

But one person can create multiple invites

#

On the other hand one invite can only point to one channel so it's better to think of invites as associated with a channel rather than a member

#

A guild being at the max amount of invites, 1000, doesn't matter

ebon island
#

What is the best way to listen to a VoiceChannel and do something when a member joins or leaves a specific voice channel?

Ideally, the behavior I would like is as follows:

Establish a channel and create an event listener for that channel in particular as a rather than a chain of similar cases like if channel_id==xyz in the body of a general method handling a voice state change over the whole channel, if there are many different channels that sounds like an awful way of handling individual channels
one idea I had was to create a channel object and somehow establish a listener pattern within it but not sure how to manage that, although that would certainly be a nice way of doing things if anyone has ideas on that?

looked at the following link:
https://discord.com/developers/docs/resources/voice#voice-state-object

I notice you get a dict with the channel id and all
so I can definitely process that
but I'd like to find means by which to do so efficiently - any ideas?

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

sick birch
foggy merlin
vocal plover
#

it wouldnt because you didnt make the invite

foggy merlin
#

so how do invite trackers know?

vocal plover
#

by looking at which invite was used and who created that invite

#

if person A creates an invite and person B sends it to person C who joins with it, it's effectively person A who invited C

sick birch
pliant gulch
#

discord gives no good way of telling if an invite was used, other than invite count

#

But that isn’t very good either

velvet compass
unkempt canyonBOT
vocal plover
#

The only effective way of tracking invites is to go through an OAuth flow on a bot's website because then the bot gets explicit info

vocal plover
sick birch
#

Say you have these invites:
X - 1 use
Y - 1 use
Z - 2 uses

now say a member joined, this is how the invites look like now:
X - 2 uses
Y - 1 use
Z - 2 uses

Now you know that the user joined using invite X

tame nymph
#

What is the length of invites

foggy merlin
tame nymph
#

Like if let’s say I’m generating random invite codes how would I implement it

foggy merlin
#

I would just know which invitation was used

pliant gulch
vocal plover
#

Discord really frowns upon invite-for-reward servers, my advice would be to just not do that at all

tame nymph
#

I need to implement an algorithm to generate random discord invite codes

vocal plover
vocal plover
#

You don't get to choose Discord invites so you'd have to let discord generate them for you

tame nymph
honest shoal
vocal plover
#

I'm not sure I understand, you need to create random invalid discord invite codes for fiverr?

tame nymph
#

8 characters long Base64?

tame nymph
#

And they could be valid right

vocal plover
#

This sounds either useless or malicious, likely the latter, so I'm afraid out of an abundance of caution I won't be able to help

tame nymph
#

Ok I guess let me ask this order guy a bit more

honest vessel
spring flax
#

this raises type object is not iterable in the send

                    all_pages = []
                    for chunk in [all_snippets[i : i + 5] for i in range(0, len(all_snippets), 5)]:
                        page = disnake.Embed(title=f"Snippets [{len(all_snippets)}]", color = disnake.Color.blurple())

                        for snippet in chunk:
                            page.add_field(
                                name=snippet[0],
                                value=snippet[1][:117] + "..." if len(snippet[1]) > 120 else snippet[1])

                        page.set_footer(text="Use the buttons to flip pages.")
                        all_pages.append(page)
                    
                    if len(all_pages) == 1:
                        all_embeds = all_pages[0]
                    else:
                        all_embeds = [embed for embed in all_pages]
                    await ctx.send(embed=all_embeds[0], view=Menu(all_embeds))
true salmon
#

is there a way to group commands in nextcord?

tame nymph
#

Nvm

#

Anyways

vocal plover
flat solstice
#

anyone got any examples of auto complete in action? I'm not really sure what the difference is between choices and auto complete as they seem rather similar

vocal plover
true salmon
vocal plover
#

if you're using cogs you should be able to use @commands.group() instead of @commands.command()

unkempt canyonBOT
#

@slate swan, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

true salmon
#

currently im using bot.getCommand("commandname").module

flat solstice
vocal plover
true salmon
#

can I add a group name?

slate swan
#
Ignoring exception in command role:
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\. InviteMnger\main.py", line 370, in role
    web = DiscordWebhook(url="LINK HERE - Canary I Used",
NameError: name 'DiscordWebhook' is not defined

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

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'DiscordWebhook' is not defined
true salmon
#

how do I get the group?

#

so the name of the group from the command?

#

how do I get that

vocal plover
#

I'm not sure what you mean

true salmon
#

so I got a discord command as a variable

#

and I want to get the group of the command

vocal plover
#

if a command is part of a group then its parent attribute will be the group

tardy atlas
#

Is it possible to make the replit bot work 24/7?

true salmon
#

also I can't set the footer if an embed

vocal plover
#

you have to use embed.set_footer() to set the footer

#

!d nextcord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
royal jasper
#

how can i unban a member? when i try member.unban(reason=None) return invoke error

vocal plover
#

you have to unban via a guild object since someone who is banned cannot be a member

#

!d discord.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

you can pass a discord.Object() into the ban method in place of an actual user/member object

slate swan
#
Ignoring exception in command role:
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\. InviteMnger\main.py", line 370, in role
    web = DiscordWebhook(url="LINK HERE - Canary I Used",
NameError: name 'DiscordWebhook' is not defined

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

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'DiscordWebhook' is not defined

Any1 know ive tried

vocal plover
#

DiscordWebhook isn't a thing, you're probably looking for just Webhook

#

which you need to import from discord/nextcord/disnake/your library of choice

tame nymph
#

Can you join a server doing POST/api/v9/invites/{invite_code} ?!?!

vocal plover
#

no

tame nymph
#

I’m getting confused

#

My friend said I can

vocal plover
#

bots can only join servers by being added by someone with permissions

slate swan
#

ey, im extremely new to python

flat solstice
#

so I have a list of cogs that my bot loads stored in a config.py file. I'm working on making commands to load/unload/reload cogs and felt that using the choices class made the most sense bc it could provide the user with a list of my cogs but I'm not sure which implementation of choices https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6#choices would be the best to use for my use case (keep in mind the cogs are stored in the list as "cogs.cog_name" so I'll need to do some string splitting to remove the "cogs." part from the lists strings

true salmon
#

set_footer needs 1 argument but recieves 2?

slate swan
#

Does anyone know who i have an error here?

honest vessel
slate swan
#

anyone know what causes that error

tame nymph
honest vessel
#

yes u dont use " " @slate swan

honest vessel
#

url=f"{ngrok}/voice"

slate swan
#

think i fixed it

#

just testing

tame nymph
#

Bruh this guy has like $1000 USD budget and he wants a bot that joins server and DMs every member invite

#

What do I do

#

Decline?

honest vessel
#

@tame nymphleave this server or stop talking abotu it.

vocal plover
#

Tell him no

#

because that's against Discord's terms of service

tame nymph
#

Ok

honest vessel
#

and clearly not a task for you anyway if u need to come here ask for help.

slate swan
#

@vocal plover it is a thing btw i fixed it i imported the wrong thing

vocal plover
#

awesome :P

tardy atlas
#

Is it possible to make the replit bot work 24/7?

vocal plover
#

it is possible (variety of methods can be found online) but if at all possible I'd highly recommend not using it since it is both underpowered and uses a few shared IP addresses across its hosts which means a hight chance of your bot being banned or ratelimited because of other people's badly behaving bots

cold sonnet
#

yes, until it gets banned

honest vessel
#

!vps

slim ibex
tardy atlas
#

@vocal plover

vocal plover
#

I have my own server that I put in a datacenter so I'm probably not the best role model here kek, but I'd recommend looking at the free tiers of AWS, Google Cloud, and Azure, and possibly Linode

tardy atlas
#

Ok

terse blade
#
    await coro(*args, **kwargs)
  File "D:\Discord BOT\main.py", line 62, in on_message
    await update_Data(USERDATA, message.author)
  File "D:\Discord BOT\main.py", line 46, in update_Data
    if not user.id in USERDATA:
ValueError: I/O operation on closed file.```
whats this
vocal plover
#

if that the full traceback? it looks like you've closed a file and then tried to read/write to it

terse blade
#

HEHH

#

how could i have closed a file

slim ibex
#

if you used a context manager, it closes the file after exiting the scope of the manager

terse blade
#

What like atom?

slim ibex
#

??

terse blade
#

whats a context manager?

slim ibex
#

how do you open youtr file

terse blade
#

idle python?

slim ibex
#

in code...

terse blade
#

F5?

slate swan
#

uij

#

mi,klæ

slim ibex
terse blade
#

it just dumps and takes stuff into it and from it

slim ibex
#

yeah the file has to be opened to do shit with it...

terse blade
#

how?

hoary cargo
slim ibex
#

ares lol

hoary cargo
#

🗿

terse blade
#

how.

hoary cargo
terse blade
#

what?

slate swan
#

Hello, im new to python. Anyone know hy this is giving errors?

#

i installed the required stuff, the dev from github told me to

slim ibex
hoary cargo
# terse blade what?

you try to write data in a file. you need to open the file first, then write what you want and close the file. it's simple and logic as that.

slim ibex
#

and what are you doing with flask

slate swan
slim ibex
#

restart vscode

slate swan
hoary cargo
slim ibex
#

choose an interpreter again

slate swan
#

if i install again, it just says requirement already satisfied

slim ibex
#

CTRL+SHIFT+P and type python, then select interpreter

terse blade
#
        user_data = json.load(USERDATA)```
slim ibex
#

that is a context manager

#

outside the scope of that statement, you can no longer so stuff with the file (although the variable isn't destroyed)

terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\client.py", line 531, in _run_event
    await coro(*args, **kwargs)
  File "D:\Discord BOT\main.py", line 63, in on_message
    await update_Data(USERDATA, message.author)
  File "D:\Discord BOT\main.py", line 47, in update_Data
    USERDATA[user.id] = {}
TypeError: '_io.TextIOWrapper' object does not support item assignment```
slate swan
#

Is ctx.author.edit a thing?

vocal plover
terse blade
#

wym

vocal plover
#

USER_DATA is a file object created by open(), it is not the dictionary you created using the data from that file

terse blade
#

so i do USER_DATA not user_data

vocal plover
#

That's what you're doing currently

#

you need to use user_data[user.id] = ... instead

cerulean elbow
cerulean elbow
slate swan
modest plover
#

i asked in a help channel but got nothing. how do i make a colour info command using pillow?

import disnake
from disnake.ext import commands
import PIL

class colours(commands.Cog):
    """A set of colour commands."""
    
    def __init__(self, bot: commands.Bot):
        self.bot = bot
    
    @commands.slash_command()
    async def colours(self, inter):
        pass
    
    @colours.sub_command()
    async def hex(self, inter, bot, hex: str):
        colourEmbed = disnake.Embed(
            title = hex,
        colour = f"")
terse blade
cerulean elbow
terse blade
#

eh

#

hold on

cerulean elbow
slate swan
#

oh yeah

#

bot uses that for commands

#
@commands.has_permissions(administrator=True)
async def nick(ctx, member: discord.Member = None,  *, nick,):
 if member == None:
    await ctx.author.edit(nick=nick)
    embed = discord.Embed(title="", description=f'**Name for {ctx.author.mention} has been changed!**', colour=0x992d22)
    await ctx.send(embed=embed)
 else:
     await member.edit(nick=nick)
     embed = discord.Embed(title="", description=f'**Name for {member.mention} has been changed!**', colour=0x992d22)
     await ctx.send(embed=embed)```

**Why does this command only work if the user pings a other guy but if he doesnt ping someone it doesnt change his nick name?** it doesnt give me a error
cerulean elbow
slate swan
#

they are giving me errors

#

I even did these installs pip install twilio pip3 install discord pip install -U discord-py-interactions

terse blade
#

what is json docs

cerulean elbow
slate swan
#

yup

#

on all of them

cerulean elbow
cerulean elbow
slate swan
#

like its imported several places or

vocal plover
#

A service that lets you make automated texts or phone calls

slate swan
slate swan
#

Just like textnow n stuff

#

automated messages

cerulean elbow
slate swan
#

yeah there is commands, but twilio is for that stuff. U make a command, and trough twilio API, u can send SMS, make voice calls, TTS

#

etc.

#

twilio gives you your own private phone number

cerulean elbow
slate swan
#

these imports are just pissing me off, dosent make any sense

cerulean elbow
slate swan
#

that just causes more errors in the code

cerulean elbow
slate swan
#

its like, the code know im using the library, but detetcs it as not installed

cerulean elbow
slate swan
#
  File "C:\Users\frede\Desktop\OTP-Bot-main\bot.py", line 67
    url=f{ngrok}'/voice',
         ^
SyntaxError: invalid syntax```
#

thats the error, no idea why its there

cerulean elbow
slate swan
#

VS code

magic ore
#

you forgot the opening quote/you have it at the wrong place

slate swan
#

how to install python in replit with using command npm i ?

cerulean elbow
slate swan
#

i have node.js already but my discord bot require python

slate swan
cerulean elbow
slate swan
magic ore
#

you should ask the person who made it

cerulean elbow
cerulean elbow
echo wasp
#

who knows pymongo?

flat solstice
#

Can I take this looppy for entry in initial_extensions: cog = entry.strip('"').split('.')[1] Choice(name=cog.title(), value=entry), cogs.append(choice)and turn it into a concatenated(?) loop like thispy cogs = [cog.strip('"').split('.')[1] for cog in initial_extensions]and if so does someone mind telling me how bc I can't wrap my head around it

modest plover
tardy atlas
#
warning = cursor.execute('SELECT * FROM banwords WHERE userid = ?', (message.author.id,)).fetchone()
2022-03-15T20:51:22.447042+00:00 app[worker.1]: psycopg2.errors.SyntaxError: syntax error at end of input
2022-03-15T20:51:22.447042+00:00 app[worker.1]: LINE 1: SELECT * FROM banwords WHERE userid = ?
2022-03-15T20:51:22.447042+00:00 app[worker.1]:                                                ^   

postgresql
How to fix.

flat solstice
terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 27, in on_message
    user_data = json.load(USERDATA)
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'```
wtf does this mean
flat solstice
#

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

terse blade
#
async def on_message(member):
    with open('users.json') as f:
        users = json.load(USERDATA)


    async def add_experience(users, user, exp):
        users[user.id]['experience'] + exp
        print(exp)
flat solstice
#

I'm not massively familiar with using json files but isn't it users=json.load(f)
Someone correct me if I'm wrong

terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 27, in on_message
    users=f.load(USERDATA)
AttributeError: '_io.TextIOWrapper' object has no attribute 'load'```
slate swan
terse blade
slate swan
flat solstice
slate swan
terse blade
slate swan
#

not what i ment

honest vessel
#

!e
import discord
print(help(discord))

unkempt canyonBOT
#

@honest vessel :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
slate swan
#

🗿

dusk karma
#

Traceback (most recent call last): File "/home/runner/nitr0h/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/runner/nitr0h/cogs/clean.py", line 12, in clear await ctx.reply("Got it. Clearing {} messages... 🧹".format(amount), delete_after=3) AttributeError: 'Clear' object has no attribute 'reply'

honest vessel
#

ah shit i wish this would work show that u can import lib n check help file aka "man in linux"

terse blade
#

ok so

honest vessel
#

'Clear' object has no attribute 'reply'

#

wtf

#

oh u forgot close it )

flat solstice
#

Can I take this looppy for entry in initial_extensions: cog = entry.strip('"').split('.')[1] Choice(name=cog.title(), value=entry), cogs.append(choice)and turn it into a concatenated(?) loop like thispy cogs = [cog.strip('"').split('.')[1] for cog in initial_extensions]and if so does someone mind telling me how bc I'm struggling to wrap my head around it but my brains telling it could be this,py cogs = [Choice(name=cog.strip('"').split('.')[1].title(),value=cog) for cog in initial_extensions]

honest vessel
#

@dusk karma

tidal hawk
#

I used set_image for embed but some images still appear outside the embed

#

May the image size be the cause?

dusk karma
flat solstice
#

what are you trying to do, detect if 'discord.gg' is in a message's contents?

#

so what's the problem with it atm, producing any errors or just not firing? if your trying to pick up a mention remove the ! from the mention as it won't be detecting that as a proper mention

cerulean elbow
flat solstice
#
elif client.mention in message.content:```try this
cold sonnet
#

client.user

#

or

cerulean elbow
#

Bot.user

cold sonnet
#

if client.user.mentioned_in(message.content):

#

which is idk why

#

oh I know, this also triggers on everyone pings

slate swan
#

How would I get this to work py @client.event async def on_message(message): if message.channel.id == 942045216658051072: await message.add_reaction("🐒") . await message.add_reaction("😉") await client.process_commands(message)

terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 46, in on_message
    await update_Data(users, message.author)
NameError: name 'message' is not defined```
#

why is message not defined?

terse blade
#
        await update_Data(users, message.author)```
cerulean elbow
slate swan
slate swan
terse blade
terse blade
#

isnt a command

slate swan
#

the function params*

terse blade
#

@bot.event
async def on_message(member):

slate swan
#

change member to message so message will be the param of the function its basic oop

cerulean elbow
#

i can also help with that 👍

slate swan
#

solve itlemon_thinking

haughty quartz
#

how can i edit a message with tasks.loop ?

#
@tasks.loop(seconds=5)
async def idk(ctx):
    await ctx.message.edit(content="foo")
@bot.command()
async def test(ctx):
    await ctx.send("hey")
    idk.start()
#

that's my take

lusty sky
#

Anyone know why my clear message command wont work?

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

@client.command()
async def clear(ctx, amount=30):

await ctx.channel.purge(limit=amount+1)
haughty quartz
#

tried that too but it didnt work

terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 52, in on_message
    await level_up(users, message.author, message.channel)
TypeError: level_up() missing 1 required positional argument: 'exp'```
vocal plover
#

As the error message says, you're missing an argument in the function being called, you need to provide a value to exp

slate swan
unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
vocal plover
#

Evidently not

terse blade
#

exp = (randint(10,50))

#

can i not use this as a value?

vocal plover
#

You need to provide it as a function argument, setting it as a variable won't work

slate swan
#

and why are you making it a tuple lol

terse blade
#

wym tuple?

vocal plover
#

that's not a tuple, since it's just wrapped in parentheses as a single object without a comma the parentheses are ignored

#

they are, however, unnecessary

slate swan
terse blade
vocal plover
#

it's pretty confusing tbh, such a change in behaviour between almost identical source

vocal plover
haughty quartz
slate swan
vocal plover
#

that way you're passing the value of exp into the function

slate swan
vocal plover
#

indeed

slate swan
#

let me show a good example

#

!e print({1: 2} | {1: 3}[1])

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: unsupported operand type(s) for |: 'dict' and 'int'
slate swan
unkempt canyonBOT
#

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

3
#

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

python for example
terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 52, in on_message
    await level_up(exp, users, message.author, message.channel)
  File "D:\TEST BOT\main.py", line 46, in level_up
    await message.send(channel, '{} has leveled up to {}' .format(user.mention, str(lvl_end)))
AttributeError: 'int' object has no attribute 'send'```
#

im so confused

slate swan
#

message is an int

terse blade
#

Yh it's ment to be

haughty quartz
slate swan
terse blade
haughty quartz
slate swan
terse blade
#

I'm so dumb allow it 😭

slate swan
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
slate swan
#

message is an instance of the Message obj

haughty quartz
# slate swan

yep ik but what discord permission is that (if u know which one it is)

slate swan
slate swan
haughty quartz
#

aight

slate swan
#

maybe it cant see the channel idk

haughty quartz
#

Cannot edit a message authored by another user can't the bot edit its own messages

slate swan
#

it can, maybe you tried to edit a message that wasnt the bots

haughty quartz
#

nah it was

#

double checked

#

and tried again

slate swan
#

why else would it raise the error then? im not sure why it would raise that error for any other reason

haughty quartz
#

yeah well same

#

no idea

slate swan
#

¯_(ツ)_/¯

haughty quartz
#

@slate swan u need that helper role lmfao i always see u in this chat when asking for help

slate swan
narrow grail
#
ctx.message.author.voice.voice_channel```  "VoiceState" object has no attribute 'voice_channel'. How to fix it?
slate swan
#

well the VoiceState class doesnt have that attr hence why the error was raised

narrow grail
slate swan
#

sorry i cant help much with that ive never gone to the voice category AG_PeepoShrug

narrow grail
#

np

slate swan
#

how can you do a discord dropdown menu in a cog?

#

hm im gonna try it

slate swan
#

no need just make the class outside of it and then just use the class lol

quaint epoch
slate swan
#

which would say NoneType doesnt have such an attr

slate swan
slate swan
#

like of what

#

pardon?

#

outside from what?

#

of the cog

#

alrdy tried that but theres a few problems with my on message

#

show

#
    raise discord.ClientException(f'Callback for {self.name} command is missing "ctx" parameter.')
discord.errors.ClientException: Callback for menu command is missing "ctx" parameter.
#
@client.event
async def on_message(message):
        results = collection_prefix.find({"guild_id":message.guild.id})
        for result in results:
            pass
        if result["prefix"] == "":
            client.command_prefix = dprefix
            await client.process_commands(message)
        else:
            client.command_prefix = result["prefix"]
            await client.process_commands(message)
slate swan
#

yeah im alrdy using a db

#

mongodb

#

!d discord.ext.commands.Bot.get_prefix

unkempt canyonBOT
#

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

Retrieves the prefix the bot is listening to with the message as a context.
slate swan
#

use this then ^

#

i got the get_prefix function

#

but i didnt use it but ima do it now

slate swan
#

btw im using cooldown Mapping with @commands.check

slate swan
#

ah

#

and idk how to reset it inside the command

#

how are you setting the cooldown

#

hol on

#

lemmee show u wut it loosk like

#
class is_premium:
  def __init__(self, rate, per, rate1, per1, guilds: list):
    self.bucket_type = commands.BucketType.guild
    self.cooldown = commands.CooldownMapping.from_cooldown(rate, per, self.bucket_type)
    self.premium_cooldown = commands.CooldownMapping.from_cooldown(rate1, per1, self.bucket_type) 
    self.guilds = guilds
    
  def __call__(self, inter: disnake.Interaction):
    key = inter.guild_id
    if key in self.guilds:
      bucket = self.premium_cooldown.get_bucket(inter)
    else:
      bucket = self.cooldown.get_bucket(inter)
      
    retry_after = bucket.update_rate_limit()
    if retry_after:
      raise commands.CommandOnCooldown(bucket, retry_after, self.bucket_type)
  
    return True```
#

what exactly are you trying to do? get the commands cooldown and then reset it?

flat solstice
#

If I declare a embed as py embed = discord.Embed(timestamp=datetime.datetime.now())can I then do py embed.title("A super cool title") embed.description("A cool description") embed.colour(discord.Colour.green())later on in the code without needing to set a new embed var

slate swan
#

yeah you can

flat solstice
#

oh cool, didn't know that until recently when I saw another bot doing it, this is going to make making embeds so much quicker

slate swan
slate swan
manic wing
#

you wouldnt call it

#

its an str that you set, not call

#

embed.description: str = …

slate swan
#

ah yeah thats right ^

flat solstice
#

okay thanks for the help

flat solstice
manic wing
#

putting () around an str does nothing

#

only when you add a trailing comma does it tupilize

flat solstice
#

👍

rocky trench
#

Nobody needs help? Kinda dead here sad_kermit

slate swan
#

I need some help here.

slate swan
#

i need some help with adding this, if you type a wrong word that isnt on the code list, my bot says invalid word please try again

rocky trench
slate swan
rocky trench
rocky trench
#

Yeah

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

rocky trench
#

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

#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1647467257:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 160 newlines in 10s).

slate swan
#

riprooSnap

hollow quarry
#

!unmute 817437509607882752

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.

slate swan
#

oh thanks

hollow quarry
#

!paste Please use this @slate swan

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
left crater
#

!d discord.ext.commands.cooldown

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

if you write senw, that isnt on in my code so my bot will say , Invalid please try again

slate swan
slate swan
slate swan
slate swan
# slate swan could i get an example
if message.content.lower() in word_list:
    await message.channel.send("ok")
else:
    await message.channel.send("Invalid please try again")

something like this

slate swan
terse blade
#

im so lost

slate swan
#

name: str is a type hint which falls into annotations and () -> None is the return type annotation which just shows what the method will return

hardy wing
#

for registering your bot on top.gg how would you make sure your bot follows api rate limits

slate swan
#

!pep 484

unkempt canyonBOT
#
**PEP 484 - Type Hints**
Status

Final

Python-Version

3.5

Created

29-Sep-2014

Type

Standards Track

slate swan
#

for more info on it^

slate swan
#

bro its an example.

terse blade
#

Traceback (most recent call last):
File "D:\TEST BOT\main.py", line 25, in <module>
async def on_message(message: Message) -> str:
NameError: name 'Message' is not defined

slate swan
#

well the class isnt defined simple.

terse blade
#

so

slate swan
#

just do message: discord.Message since you arent importing the class and are you sure that return type is correct?

terse blade
#

i dont know

#

i legit have the same error i had at the start 🤣

#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 52, in on_message
    await level_up(exp, users, message.author, message.channel)
  File "D:\TEST BOT\main.py", line 46, in level_up
    await message.send(channel, '{} has leveled up to {}' .format(user.mention, lvl_end))
AttributeError: 'int' object has no attribute 'send'
slate swan
slate swan
terse blade
#

just makes no sense

slate swan
#

its simple oop an int doesnt have that method

terse blade
#

ENGLISH?

slate swan
#

yes its in english

terse blade
#

it isnt

slate swan
#

its just terms lol

echo wasp
#

hello, i have a question how do i get the content of this message &enable hello world

slate swan
unkempt canyonBOT
echo wasp
terse blade
#
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 50, in on_message
    await update_Data(users, discord.Message.author)
  File "D:\TEST BOT\main.py", line 31, in update_Data
    if not user.id in users:
AttributeError: 'member_descriptor' object has no attribute 'id'```
#

??

slate swan
terse blade
#

Ok one last time

#

That dosent HELP

echo wasp
slate swan
terse blade
#

thanks for telling me something ive read

slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'list' object has no attribute 'split'
slate swan
terse blade
#

dosent make sense to me

final iron
terse blade
final iron
#

That's why it makes no sense

slate swan
#

then you should learn some dpy is all about oop

final iron
#

This library is heavily based on oop

rocky trench
#

You split into a list, u can't split a list

slate swan
echo wasp
slate swan
sick birch
# terse blade no

That's probably why. You'll get stuck at really simple problems if you don't know OOP. This library is not a beginner's library, it involves many advanced topics and OOP is one of them. You could save yourself a lot of headache by learning some OOP first before attempting discord bots with discord.py

rocky trench
#

What was OOP again?

slate swan
#

object oriented programming

echo wasp
slate swan
rocky trench
#

I mean I started with dpy before learning python basics 😅

slate swan
sick birch
vocal plover
#

Here's a great video on OOP: https://www.youtube.com/watch?v=ZDa-Z5JzLYM

In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.

Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...

▶ Play video
rocky trench
#

I learnt them all after, biggest regret of my life that I skipped over them

rocky trench
#

Basics are very important and with basics, it would've gone way faster

#

Been coding for 3 years now

slate swan
#

corey is the best on tutorials no joke

slate swan
vocal plover
#

mine are pretty good too mmLol

echo wasp
rocky trench
slate swan
slate swan
slate swan
vocal plover
#

I keep meaning to do more and then ending up really depressed and don't want to do them lmao

rocky trench
# slate swan same

Classes and subclasses is the things I don't get, like why do you use them

slate swan
echo wasp
slate swan
rocky trench
manic wing
rocky trench
#

Ive been focused on library's like selenium web scraping and dpy

terse blade
#
Traceback (most recent call last):
  File "C:\Users\hustl\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\TEST BOT\main.py", line 50, in on_message
    await update_Data(users, discord.Message.author)
  File "D:\TEST BOT\main.py", line 31, in update_Data
    if not user.id in users:
AttributeError: 'member_descriptor' object has no attribute 'id'```
??
manic wing
#

do you use global instead?

rocky trench
rocky trench
terse blade
#
async def on_message(message: discord.Message) -> None:
    with open('users.json') as f:
        users=json.load(f)
    

    async def update_Data(users, user):
        if not user.id in users:
            users[user.id] = {}
            users[user.id]['experience'] = 0
            users[user.id]['level'] = 1


    async def add_experience(users, user, exp):
        users[user.id]['experience'] + exp

    async def level_up(message: discord.Message, users, user, exp):
        experience = users[user.id]['experience']
        lvl_start = users[user.id]['experience']
        lvl_end = int(500)
        
        if lvl_start < lvl_end:
            await message.send(channel, '{} has leveled up to {}' .format(user.mention, lvl_end))
            users[user.id]['level'] = lvl_end

    with open('users.json') as f:
        await update_Data(users, discord.Message.author)
        await add_experience(users, discord.Message.author, exp)
        await level_up(exp, users, discord.Message.author, discord.Message.channel)  ```
manic wing
rocky trench
terse blade
rocky trench
rocky trench
slate swan
terse blade
manic wing
slate swan
#

i mean classes are so good thoooo so i stand by him

rocky trench
manic wing
#

x = "hi" is an object of class str

rocky trench
#

God

slate swan
#

!e print(int)

unkempt canyonBOT
#

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

<class 'int'>
rocky trench
#

I see i see

manic wing
#

bertie

slate swan
#

its basic py

terse blade
rocky trench
#

Now what should I replace 'global' with?

slate swan
manic wing
rocky trench
manic wing
rocky trench
slate swan
rocky trench
#

async def init PES_Angel

terse blade
rocky trench
terse blade
slate swan
#

still not a db

terse blade
#

its a temp one

slate swan
#

a database is ment to store data unlike json

flat solstice
#

s it possible to use self in a deco? I have this deco in which I want to use selfpy @app_commands.choices(cogs=[Choice(name=cog.split('.')[1].title(),value=cog) for cog in self.bot.initial_extensions])

rocky trench
#

Waste of time

#

Just move to sql if u want a good quality database

terse blade
flat solstice
slate swan
terse blade
#

sql is sad

slate swan
#
warning = cursor.execute('SELECT * FROM banwords WHERE userid = ?', (message.author.id,)).fetchone()
2022-03-15T20:51:22.447042+00:00 app[worker.1]: psycopg2.errors.SyntaxError: syntax error at end of input
2022-03-15T20:51:22.447042+00:00 app[worker.1]: LINE 1: SELECT * FROM banwords WHERE userid = ?
2022-03-15T20:51:22.447042+00:00 app[worker.1]:                                                ^   

postgresql
How to fix.

terse blade
#

its old

slate swan
#

bro what

#

do you know what youre talking about bro

manic wing
#

!e ```py
from future import annotations

class :
def init(
: , ): .=; .=

def pow(
: , __): return .**__
print.call(___(2) ** 2)```

unkempt canyonBOT
#

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

4
flat solstice
#

okay next question, is importing my bot var into a cog file a bad idea / bad practice (for use in a deco)py from main import bot

rocky trench
slate swan
rocky trench
terse blade
slate swan
slate swan
terse blade
slate swan
#

shit posting rn

flat solstice
terse blade
#

still old

slate swan
#

you really dont know what youre talking about lmfao

terse blade
#

yes i dont have a pissing clue

full lily
rocky trench
full lily
#

Do you see the issue with that statement?

slate swan
rocky trench
flat solstice
# slate swan why would you need to import it

so is it a bad idea? I assume it's bad practice but will it have any knock on effects? would I avoid any potential knock on effects by just importing that the specific attribute I need from the bot var?

rocky trench
#

U don't need a bot var in cogs

#

U just need ur commands from discord.ext

slim ibex
#

What’s going on

slate swan
slate swan
rocky trench
slate swan
#

Code only nicks the author and ignores if a user was mentioned, i tried switching it to if member is None: did the same thing, please tell me what i did wrong

flat solstice
rocky trench
#

Not if member is None

slate swan
#

so no checking for it

slim ibex
rocky trench
#

None & not None ≠ True & False

slate swan
rocky trench
#

Or am I wrong?

slate swan
#

no youre right

#

theyre both different objs

rocky trench
slate swan
#

but None is falsy

#

but is compares objs so it wouldnt be the same

rocky trench
#

Yeah, I explained it bad again

slate swan
#
warning = cursor.execute('SELECT * FROM banwords WHERE userid = ?', (message.author.id,)).fetchone()
2022-03-15T20:51:22.447042+00:00 app[worker.1]: psycopg2.errors.SyntaxError: syntax error at end of input
2022-03-15T20:51:22.447042+00:00 app[worker.1]: LINE 1: SELECT * FROM banwords WHERE userid = ?
2022-03-15T20:51:22.447042+00:00 app[worker.1]:                                                ^   

postgresql
How to fix?

leaden jasper
#

sql syntax error

#

What is ?

#

Oh I think it's %s

slate swan
#

._.

slow fog
terse blade
#

how to use slash commands with d.py?

slate swan
#

i think its $#

#

🤔

slate swan
#

i suppose yes

slow fog
terse blade
slate swan
terse blade
#

?

slate swan
#

i ment dpy 2.0

terse blade
#

wait

slate swan
leaden jasper
terse blade
slow fog
flat solstice
#

random question, is there a particular codeblock format that is good as displaying tracebacks?

slate swan
slow fog
#

its like

int var
("%s",var)
lol

terse blade
#

1.7.3

leaden jasper
slate swan
terse blade
#

how to update it?

slate swan
terse blade
#

so copy and paste it?

pliant gulch
#

You could clone it, but it's a lot easier to pip install git+repo

slate swan
slate swan
flat solstice
slate swan
flat solstice
#

oh okay, thought you meant a standard codeblock lang, not the literal default codeblock

pliant gulch
#

discord supports most of the syntax higlighting shown in hightlight.js

sick birch
terse blade
#

whats repo?

slow fog
#

lol

terse blade
#

allow it 😭

pliant gulch
#

The github repo link

terse blade
#

so this?

pliant gulch
#

Correct

#

After you install from here, you should probably uninstall your old version of discord.py

terse blade
pliant gulch
#

Install git

terse blade
#

WHAT???

#

please speak some english

slate swan
terse blade
pliant gulch
#

Uh... I am speaking english

#

Just install git, perhaps do a reboot to ensure it's on PATH

slate swan
pliant gulch
#

then run the command again

terse blade
#

install git?

pliant gulch
#

Yes

terse blade
#

is that the command?

slate swan
pliant gulch
terse blade
#

instal

pliant gulch
#

Yes

terse blade
pliant gulch
#

Yes...

terse blade
#

thats the command?

pliant gulch
#

No, you go to the website

#

And isntall git, the program

terse blade
#

and download it?

#

so download it

pliant gulch
#

Yes

terse blade
#

well its funny how i downloaded it and it still didnt work

slate swan
#

hi how can i get avatar url from bot? client.user.avatar_url doesnt work

sick birch
slate swan
#

im on discordpy 1.7.3

#

can i download discordpy 2.0 trough git?

sick birch
#

I see, how does it "not work" by the way?

slate swan
#
@client.event
async def on_message(message):
    if message.channel.id == 942045216658051072:            
        await message.add_reaction(":monkey:953747076917887077")
        await client.process_commands(message)``` can someone explain why this says unknown emoji? and whenever I try use other commands it doesn’t work ?
terse blade
#

so how do i do a slash command now?

slate swan
#

i have no idea why this doesnt work

slate swan
sick birch
#

Yeah that's not right

slate swan
#

just type \ and a emoji

#

then put that text on the message.add_reaction

#

Okay but how would I fix it from stopping my other cmds working

pliant gulch
slate swan
#

no I want it so it only auto reacts in that channel however all my other commands stop working

slate swan
slate swan
slate swan
pliant gulch
slate swan
#

\🐒

#

It does that ?

#

use emojis from this srv

sick birch
slate swan
terse blade
#

HOW TO DO A SLASH COMMAND

slate swan
slate swan
#

Okay but how would I fix my other commands because none of them are working

slate swan
#

here

terse blade
#

HOW TO DO A SLASH COMMAND

slate swan
#

does this work

sick birch
slate swan
#

i think i now why my bot has a default pfp

sick birch
#

I don't think that's the issue

slate swan
sick birch
#

Try it for yourself

#

member.avatar_url maybe?

#

see if it works on non bots

slate swan
slate swan
#

just wait a few minutes

#

okay

terse blade
#

HOW TO DO A SLASH COMMAND

slate swan
#

it doesnt work for me too

slate swan
#

avatar_url

#

send code

terse blade
#

HOW TO DO A SLASH COMMAND

sick birch
slate swan
# slate swan send code
@client.command()
async def test(ctx):
    await ctx.send(ctx.author.avatar_url)

just tried to see if it displays my av but it doesnt work

#
async def avatar(ctx, member: discord.member):
    test = member.avatar_url
terse blade
slate swan
#

it works with .url tho

slate swan
#

like with avatar.url

#

but my discordpy version is 1.7.3

pliant gulch
echo wasp
#

is talk about pymongo allowed here?

slate swan
#

sure

sick birch
slate swan
sick birch
#

I'm finding plenty

sick birch
terse blade
#

I'm blind asf 🤦‍♀️

slate swan
#

im on 2.0.0b5

#

i think because of pycord

terse blade
#

Why don't people make it via atom then host layer

slate swan
sick birch
slate swan
#

yeah

pliant gulch
#

Kek

sick birch
#

Earlier you said 1.7.3 so I thought something was really broken

slate swan
#

lol i typed pip list and check my discord.py version and it said 1.7.3

pliant gulch
#

Probably because you werent looking at the pycord version

slate swan
terse blade
slate swan
#

i think it only works on embeds

#

try this

#
warning = cursor.execute('SELECT * FROM banwords WHERE userid = %s', (message.author.id,)).fetchone()2022-03-16T23:08:46.605486+00:00 app[worker.1]: AttributeError: 'NoneType' object has no attribute 'fetchone'

postgresql

#

help me pls

slate swan
pliant gulch
#

avatar_url is an Asset object, you need to cast it to str to get the actual cdn url

hot plaza
#
\u001b[0;36mHi
hot plaza
#
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
or
\u001b[1;40;32mThat's some cool formatted text right?
#

doesn't work anymore

pliant gulch
#

u001b has to be the actual character

slate swan
hot plaza
#

oh

slate swan
#
import os
os.system('cls')
pliant gulch
#
[1;32mThat's some cool formatted text right?
hot plaza
pliant gulch
#

Low effort troll

slate swan
hot plaza
#
\u001b[1;32mThat's some cool formatted text right?
pliant gulch
slate swan
#

then cls will work

pliant gulch
pliant gulch
slate swan
#

anwser

pliant gulch
#

Clearing the terminal is totally irrelevant to the current issue

#

They are using \u001b, not the ACTUAL unicode character

slate swan
pliant gulch
#

In order to use ANSI escape sequence they need the REAL character

slate swan
#

i had the same issue it wasn't printing the fromated text cls fixed it

#

it was priting the exact same but with different characters

slate swan
#

can i have a message handler inside main.py and also another message handler inside cogs?

left crater
#
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\dpamong\discord\ext\commands\core.py", line 182, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\dpamong\docs\commands.py", line 221, in channel
    cursor.execute(sql , val)
sqlite3.OperationalError: near ",": syntax error

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

Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\dpamong\discord\ext\commands\bot.py", line 1055, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\nikit\PycharmProjects\dpamong\discord\ext\commands\core.py", line 899, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\nikit\PycharmProjects\dpamong\discord\ext\commands\core.py", line 191, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: near ",": syntax error``` anyone know why this is happening
slim ibex
#

sqlite issue

#

show code

left crater
#
    async def welcome(self, ctx):
        await ctx.send("Setup welcome channel %welcome <channel>\n%welcome <welcome message>")

    @welcome.command()
    @commands.has_permissions(manage_messages=True)
    async def channel(self, ctx, channel : discord.TextChannel):
        db = sqlite3.connect("burber.db")
        cursor = db.cursor()
        cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
        res = cursor.fetchone()
        if res is None:
            sql = ("INSERT INTO main(guild_id, channel_id), VALUES(?,?)")
            val = (ctx.guild.id, channel.id )
            await ctx.send(f"Channel has been set to {channel.mention}")
        elif res is not None:
            sql = ("UPDATE main SET channel_id = ? WHERE guild_id = ?")
            val = (channel.id, ctx.guild.id)
            await ctx.send(f"Channel has been updated to {channel.mention}")
        cursor.execute(sql , val)
        db.commit()
        cursor.close()
        db.close()```i got it off a tutorial ik
slim ibex
#

or no pls don't copy tutorials

supple thorn
#

Nikit

left crater
#

?

left crater
slim ibex
#

docs exist

left crater
#

ye

#

but do you know whats wrong?

slim ibex
#

you should do your queries on one line

#

db.execute("UPDATE main SET channel_id = ? WHERE guild_id = ?", (channel.id, ctx.guild.id,))

hushed galleon
#

i dont think there's anything wrong with using variables

slim ibex
#

and the issue is that you added an extra space after sql before the comma

#

(thats what the traceback makes it seem like)

hushed galleon
#

no there shouldnt be a comma there in the first place

slim ibex
sick birch
slim ibex
#

it could be because sql is a tuple. not sure though

hushed galleon
#

INSERT INTO main(guild_id, channel_id), VALUES(?,?) the comma after channel_id isnt part of the syntax

left crater
slim ibex
#

the sql is generally a string, not a tuple

#

the arguments passed to the placeholders is a tuple

hushed galleon
slim ibex
slate swan
#

python interprets it like it wasnt their its just as said it just sets an order of each operation

slim ibex
#

good to know

left crater
#

it works i just removed the comma

#

ight thanks

hushed galleon
#

you should be using an async lib for sqlite though

slim ibex
#

^

left crater
#

which one?

slim ibex
#

!pip asqlite

unkempt canyonBOT
hushed galleon
#

e.g. aiosqlite or asqlite

slate swan
#

!e print({1: 2} | {1: 3}[1])

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: unsupported operand type(s) for |: 'dict' and 'int'
slate swan
#

!e print(({1: 2} | {1: 3})[1])

unkempt canyonBOT
#

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

3
slate swan
#

@slim ibex some examples^

slim ibex
#

👍

slate swan
#

is there a way to reset a mapping cooldown

#

commands.CooldownMapping

hushed galleon
#

are you trying to reset all cooldowns the mapping has, or just one?

#

if its just one you should preferably use Command.reset_cooldown(ctx), where the command can also come from ctx.command
to reset the entire mapping you'd need to go through the _cache and call .reset() each Cooldown object

terse blade
#

WHATS THE DOCSSSSSS

hushed galleon
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
hushed galleon
#

the embed parameter is in there

terse blade
#

ye butr

#

I need an example of a whole embed

hushed galleon
#

like which part each parameter corresponds to?

slate swan
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
slate swan
#

it explains itself lol

#

bog

tawny sorrel
#

My friend has mod and he can kick an admin, how do I fix that in python discord.py

slate swan
#

i suppose get role id for the higher up roles and disallow the command to pass through if the person has a lower rank attempting to kick admin and whatnot.. or you can do it based on permissions i believe so

tawny sorrel
slate swan
#
if member.guild_permissions.administrator: #it checks if the member has administrator permissions
  await ctx.send("You cannot ban mod/admin")```
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
worldly bane
#
if user.top_role < ctx.author.top_role:
  #ban
else:
  #ignore
#

this can work if both has ban perms or so

slate swan
slate swan
slate swan
hushed galleon
hushed galleon
slate swan
#

is there a way to reset a mapping cooldown

slate swan
slate swan
hushed galleon
#

the traceback and the code being...?

slate swan
hushed galleon
#

that error looks like you made your own custom class?

hushed galleon
#

well then where's the cooldown mapping

slate swan
#

custom buckets

#

basically wut i wanted to try is

#

yoy

#
class is_premium:
  def __init__(self, rate, per, rate1, per1, guilds: list):
    self.bucket_type = commands.BucketType.guild
    self.cooldown = commands.CooldownMapping(commands.Cooldown(rate, per), self.bucket_type)
    self.premium_cooldown = commands.CooldownMapping.from_cooldown(rate1, per1, self.bucket_type) 
    self.guilds = guilds
    
  def __call__(self, inter: disnake.Interaction):
    key = inter.guild_id
    if key in self.guilds:
      bucket = self.premium_cooldown.get_bucket(inter)
      
    else:
      bucket = self.cooldown.get_bucket(inter)
    
    bucket.reset
  
    retry_after = bucket.update_rate_limit()
    if retry_after:
      raise commands.CommandOnCooldown(bucket, retry_after, self.bucket_type)
  
    return True``` i've tried `bucket.reset` to see if it reset the cooldown but
hushed galleon
#

oh you're on disnake, that should have the dynamic_cooldown decorator forked from 2.0

#

!d disnake.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@disnake.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command "disnake.ext.commands.Command")

This differs from [`cooldown()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.cooldown "disnake.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`disnake.Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") and must return a [`Cooldown`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Cooldown "disnake.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

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://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.BucketType "disnake.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CommandOnCooldown "disnake.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
hushed galleon
#

you can return whatever Cooldown object you like based on the message

slate swan
# unkempt canyon

ion think i'll be able to make a special cooldown for special ppl with this?

hushed galleon
#

thats exactly what dynamic_cooldown is for

lusty sky
#

Can someone explain why my change nick command doesn't change someones entire name if they put a space in it somewhere

#
@client.command(pass_content=True)
async def changenick(ctx, member: discord.Member, nick):
    await member.edit(nick=nick)
    await ctx.send(f'Nickname changed for{member.mention}')```
slate swan
hoary cargo
#

Btw can delete_message_days be set to other values than the built-in? ( None, 1 day, 7 days) like delete the messages from the past 3 days hmm

pliant gulch
hushed galleon
terse blade
#
  userlvl = users[f'{ctx.author.id}']['level']
  embed = discord.Embed(
  description={
    f'Your rank is:{userlvl}'
    },
    author={
      'name':f'{ctx.author.name} Rank',
      'icon_url':f'ctx.author.avatar_url'
      },
    footer={
      'text':f'{experience}/500'
      }
  )```
whats wrong with this embed?
hoary cargo
pliant gulch
#

Well, you can do 0-7 days

#

The offical documentation says so

terse blade
#

so..

slate swan
#

command.Command.reset_cooldown(ctx) @hushed galleon

echo pivot
#

Can someone tell me what a guild is? (is it a server? channel? or something completely different?)

echo pivot
#

Thanks

slate swan
#

yw

#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

x != y Checks if two guilds are not equal.

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
hushed galleon
terse blade
#

HELLO

slate swan
terse blade
#

HELLO

hoary cargo
pliant gulch
#

👍

#

Where were you looking originally, discord.py docs?

terse blade
pliant gulch
slate swan
long wigeon
#

any discord guru here?

worldly bane
long wigeon
#

do you know anything about discord token generator?

#

or discord account creator?

supple thorn
#

Discord already does that

hushed galleon
#

or do you mean what a discord token is composed of

supple thorn
#

He wants a bunch of alts

hushed galleon
#

yeah of course

supple thorn
#

Maybe to sell or to use to raid a server

echo pivot
#

Quick question (hopefully). I have this command here, I want it to return if key or description is None. But instead it sends the first message (You must provide a key...) the proceeds to execute the second ctx.send() (You do not have permission...)
Anyone know the proper way to stop a command, like return would stop a function?

@commands.command(name='add-help')
async def add_help(self, ctx: commands.Context, key: str = None, *, description: str = None):
    if not key == None or not description == None:
        await ctx.send('You must provide a key and description when adding a help topic.\nUsage: `--add-help key description`')
        return
    await ctx.send('You do not have permission to create a new help topic.\nYour request will be forwarded to an administrator.')
final iron
echo pivot
final iron
#

You tried restarting your bot?

#

Maybe the code changes haven't applied

echo pivot
#

Yep, several times

#

I'll do it again 🤷‍♂️

#

oh

supple thorn
#

🗿

echo pivot
#

something weird is up, cause it still works when it's not running xD

#

(my remote is off too)

supple thorn
#

Remote?

#

Are you running the bot on a tv?

echo pivot
#

Remote (cloud)

supple thorn
#

Discord wonky sometimes

echo pivot
#

Ah, I had a random python instance running in the background.

#

So it was duplicating my command (but one was outdated and only had one response so it looked like I explained)

#

Classic instance of asking for help 30 seconds before I figure it out.

worldly bane
#

🗿

sick birch
lusty sky
#

What do I add to my code to make it check the person sending the command has permission?

#
@client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
    await member.kick(reason=reason)
    await ctx.send(f"Sent to the hell fire{member.mention}!")```