#discord-bots

1 messages Β· Page 528 of 1

tawdry perch
#

oh, good that you still read it

weary gale
#

smh

#

i fr coulda just pressed f5

tawdry perch
#

ye

fair wave
#

Can you please give me an example of how i run flask in the background of my discord bot

weary gale
#

if i just scrolled down like 2 lines i coulda saved all that time

#

that was so magical

#

seeing the bot go online

slate swan
#

how do you see if someone either joins through a vanity link or a bot joins through OAUTH2? I'm trying to make it so that in my invite tracker bot, it shows whether that person joined through oauth2 or vanity

weary gale
#

is this how u do it? or do i need to put the circled script below the run part

boreal ravine
wise swift
#

Command should not be indented iirc

crystal cliff
fading harness
boreal ravine
crystal cliff
boreal ravine
fading harness
#

the @bot.command arguments should be intented correctly

crystal cliff
#

@bot.command should @Bot.command and indented

reef shell
#

indent

#

!indent

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

boreal ravine
weary gale
#

uh

boreal ravine
weary gale
#

im at this, so do i remove line 6?

crystal cliff
slate swan
fading harness
#
@client.event()
async def on_ready():
  print('Bot is ready.')
@bot.command(name="hello")
boreal ravine
slate swan
#

how would i handle it

weary gale
boreal ravine
#

dont remove shit

slate swan
fading harness
boreal ravine
#

@crystal cliff did

weary gale
#

oh

slate swan
weary gale
#

in the same place?

slate swan
weary gale
slate swan
slate swan
wise swift
#

Just tap backspace before that @bot lol

weary gale
#

yeah they were both talking to me
@slate swan

fading harness
boreal ravine
fading harness
#

lets replace with his code

tropic briar
#

I get some errors on replit.com but I don't see those errors when I use Pycharm
They are runtime errors
What should I do, I am not even able to let my script running because of that error

slate swan
#

same thing with oauth

boreal ravine
#

@tropic briar python version error just switch to another repl I think

weary gale
#

what the actual

crystal cliff
weary gale
#

hOw dO i gEt tHiS tO wOrK

slate swan
#

@boreal ravine something like this

boreal ravine
slate swan
crystal cliff
boreal ravine
slate swan
crystal cliff
weary gale
slate swan
boreal ravine
weary gale
#

@boreal ravine

wheat moth
#

@weary gale replace

@client.command(name="hello")

to:

@client.command()
async def hello(ctx):
  pass
weary gale
#

ok

crystal cliff
boreal ravine
boreal ravine
#

use @bot.command() for commands

#

@bot.event is only for events

celest marlin
boreal ravine
slate swan
boreal ravine
wheat moth
#

@regal sparrow yes

boreal ravine
#

use proper formatting

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

crystal cliff
weary gale
#

doesnt work when i run the command in my server

marsh depot
# boreal ravine use proper formatting

Anyone know where is the problem?

@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None):
    if opcion1 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    if opcion2 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    else:
        eleccion = random.choice(opcion1, opcion2)
        await ctx.reply(f"**{ctx.author.display_name}** elijo **{eleccion}**")

I have this error choice() takes 2 positional arguments but 3 were given

boreal ravine
weary gale
#

yes

wheat moth
#

@marsh depot try this:

@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None):
    if opcion1 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    elif opcion2 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    else:
        eleccion = random.choice(opcion1, opcion2)
        await ctx.reply(f"**{ctx.author.display_name}** elijo **{eleccion}**")

or:

@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None):
    if opcion1 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    elif opcion2 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    eleccion = random.choice(opcion1, opcion2)
    await ctx.reply(f"**{ctx.author.display_name}** elijo **{eleccion}**")
crystal cliff
#

Is $ your default prefix?

slate swan
#

lol

boreal ravine
#

oh makes sense why it didnt output anything

#

he did pass

weary gale
#

what

odd walrus
#

what do you want ur bot to do

#

!hello then it send hello back?

boreal ravine
#

yes we know

slate swan
#

that was an example lol

boreal ravine
#

read the code

slate swan
#

AttributeError: 'Member' object has no attribute 'has_permissions'

        modRoles = data['modroles'] 
        for role in ctx.author.roles:
            if role.id in modRoles or ctx.author.has_permissions(administrator=True) or ctx.author.id == ctx.guild.owner:
                return True
            return False```

trying to make a check for a command which sees if user has a role in a db, has admin perms, or is the guild owner
boreal ravine
#

u did pass

weary gale
#

what am i supposed to put there

boreal ravine
odd walrus
#

yes pls say

weary gale
#

hi

slate swan
#

are you really that new

celest marlin
odd walrus
#

u want bot to respond hi

#

when u send !hello?

weary gale
#

yes

weary gale
boreal ravine
#

!resources @weary gale

unkempt canyonBOT
#
Resources

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

slate swan
#

replace pass with await ctx.send("Hi")

weary gale
#

thx

boreal ravine
slate swan
#

yes

boreal ravine
#

!d discord.abc.Messageable.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**.
boreal ravine
#

😐

slate swan
#

chad

celest marlin
weary gale
boreal ravine
weary gale
boreal ravine
#

bro did u even invoke the command

weary gale
#

whos that

celest marlin
slate swan
#

you need to run the bot

weary gale
#

i did

boreal ravine
odd walrus
#

did u send $hello

slate swan
#

did you save the file

boreal ravine
weary gale
#

yes

#

i saved all

#

i ran $hello in my server

#

and nothing

boreal ravine
#

restart the bot

slate swan
#

does the bot become Online

weary gale
#

y e s

celest marlin
odd walrus
boreal ravine
weary gale
celest marlin
slate swan
#

restart

weary gale
boreal ravine
#

I mean u dont need message intents

weary gale
boreal ravine
#

for a command like that

wheat moth
#

did you write exactly: "$hello" because it's case sensitive

boreal ravine
odd walrus
#

just close the script and rerun

weary gale
slate swan
slate swan
#

πŸ’€

weary gale
#

ok

boreal ravine
celest marlin
weary gale
#

i forgot what to do

#

to open it

wheat moth
#

o i know what is wrong...
change @quaint axle.command() to commands.command()

celest marlin
weary gale
#

LMAO

boreal ravine
odd walrus
celest marlin
#

JSUT STOP

slate swan
#

everyone stop with these advices

boreal ravine
#

the command

weary gale
#

no to open vsc

boreal ravine
#

isnt even

#

in a class?

slate swan
#

click on it

odd walrus
#

oh my god

weary gale
#

i thought u opened from cmd in the file.

slate swan
weary gale
#

ok whatever

odd walrus
boreal ravine
#

^

slate swan
#

in cmd

odd walrus
#

yes

boreal ravine
#

console*

slate swan
#

huh

boreal ravine
#

or shell whatever

celest marlin
#

everyone just stop helping @weary gale
they need to learn python and how the shell works before they use discord.py πŸ’€

slate swan
#

everyone gets help

weary gale
odd walrus
#

yes learn basic python first

weary gale
#

it works

boreal ravine
weary gale
#

so thats cool

hasty iron
#

typehinting isnt really required

boreal ravine
#

it isnt

#

i stole it from rdanny

#

didnt have time to edit

odd walrus
#

go to the green site

slate swan
boreal ravine
odd walrus
#

relax

marsh depot
celest marlin
boreal ravine
slate swan
#

put those in a list

#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
pulsar shell
slate swan
#

seq being a list or an array
@marsh depot

#

or a tuple

marsh depot
boreal ravine
hasty iron
#

no

#

bay zed

boreal ravine
#

sounds gay

unkempt grove
#

Hello. In which channel can I get help with discord.py?

slate swan
#

...

#

this one

odd walrus
boreal ravine
slate swan
#

we're kinda having a lot of shitposters in the moment

#

don't worry

boreal ravine
#

^

unkempt grove
#

Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: <module>)
As of 3.10, the loop parameter was removed from Event() since it is no longer necessary

class BotTask(commands.Cog):
    def __init__(self, bot, prefix):
      self.dblpy = dbl.DBLClient(self.bot, self.token) ##This line 
boreal ravine
#

hm

unkempt grove
#

Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: <module>)
As of 3.10, the loop parameter was removed from Event() since it is no longer necessary
File "C:\Users\kaspa\OneDrive\Desktop\Python Discord\app\task.py", line 18, in init
self.dblpy = dbl.DBLClient(self.bot, self.token)
File "C:\Users\kaspa\OneDrive\Desktop\Python Discord\main.py", line 93, in <module> (Current frame)
bot.add_cog(BotTask(bot, PREFIX))

slate swan
#

I've never seen anything like that

pliant gulch
#

This is just a python 3.10 deprecation error

slate swan
#

bot the documentation tells me about setting
self.token to 'dbl_token'

pliant gulch
#

as error says they removed the loop parameter from Event()

slate swan
#

or have you just removed this from your example

pliant gulch
#

I would suggest downgrading from 3.10 unless you want to go edit the internals of discord.py

slate swan
#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        db = sqlite3.connect("database.db")
        cursor = db.cursor()
        guild = self.client.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id)
        cursor.execute(f"SELECT message_id FROM ticket WHERE guild_id = {self.client.get_guild(payload.guild_id)}")
        wynik = cursor.fetchone()
        if not wynik:
            return
        else:
            for x in wynik:
                if payload.message_id == wynik:
                    if payload.emoji.name == ":white_check_mark:":
                        await member.send("Utworzyles ticketa!")```
#
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "/home/kr3mu/.local/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "/home/kr3mu/Dokumenty/DiscordBOT/TicketSystem/ticketcreate.py", line 66, in on_raw_reaction_add
    cursor.execute(f"SELECT message_id FROM ticket WHERE guild_id = {self.client.get_guild(payload.guild_id)}")
sqlite3.OperationalError: near "Server": syntax error
#

even tho...

#

you shouldn't use f-strings for executing something in a db

slate swan
#

!pypi aiosqlite πŸ€·β€β™‚οΈ

unkempt canyonBOT
kindred epoch
#

wait

#

idk what ur doing lmao

waxen granite
#
  File "/home/Mechanic/cogs/giveaway.py", line 346, in giveawaytask
    message = await giveawaychannel.fetch_message(msgid)
  File "/home/Mechanic/.local/lib/python3.8/site-packages/discord/abc.py", line 1132, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "/home/Mechanic/.local/lib/python3.8/site-packages/discord/http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
what is this error?
wispy spade
kindred epoch
waxen granite
#

these are the perms of the bot in the guild

tough wagon
#

why not to add admin perm? noone know

wispy spade
#

The list of perms should be enough I guess.

waxen granite
#

well the guild owner dont want the bot to have admin perms

kindred epoch
waxen granite
kindred epoch
tough wagon
waxen granite
# kindred epoch send ur code
    async def giveawaytask(self):
        for key in self.giveawaychan.keys():
            guild = self.bot.get_guild(int(key))
        try:
            msgid = self.giveawaychan[str(guild.id)]["giveawaymessageid"]
            chid = self.giveawaychan[str(guild.id)]["giveawaychannelid"]
            time = self.giveawaychan[str(guild.id)]["time"]
        except KeyError:
            return
        giveawaychannel = self.bot.get_channel(chid)
        message = await giveawaychannel.fetch_message(msgid)```
slate swan
#

that for loop seems really useless

kindred epoch
waxen granite
#

ye

#

it was working before

#

before the bot has less perms

#

had

wispy spade
#

might be how you added the bot to the server

#

but that's just a guess

waxen granite
#

on google it said something about syncing perms with the category but idk if thats the case here

#

channel perms*

#

for the bot role

slate swan
#

yeah , you can try viewing the guild by bot's roles and see if you can see the channel if you are an admin in the server...

waxen granite
#

how can i get the channel perms for a role?

wispy spade
waxen granite
#

i am doing it with a command

slate swan
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

slate swan
#

!d discord.TextChannel.permissions_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
waxen granite
#

i myself dont have perms to look into server stuff

slate swan
#

oh , you can use roles

marsh depot
#

Why the bot only take the first word?

My code

@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None): # COMANDO CHOOSE
    if opcion1 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    if opcion2 is None:
        await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
        return
    else:
        select = opcion1, opcion2
        eleccion = random.choice(select)
        await ctx.reply(f":Loading: Elijo `{eleccion}`", mention_author=False)
coral flame
marsh depot
#

How can i solve it?

coral flame
#

i would use wait_for to get the arguments. have the user run the command, then ask for the first one and after the second

marsh depot
#

and if i want to make all in one string? like my code?

mighty dust
#

ello

mighty dust
#

can you give link for the documentation list

#

i cant find it

valid niche
mighty dust
#

like a page with lists of all client events

#

i cant find it

mighty dust
#

found it nvm

valid niche
mighty dust
#

sorry

#

yeah

#

so sorry my bad i cant see the biggest stuff on my screen

marsh depot
#

How can i solve it? Ayone can help me?

mighty dust
#

what is Members.Intents and how do i enable it

crystal cliff
mighty dust
#

thank you

#

so much

marsh depot
#

okay, but how can i make the bot send all the first option?

slate swan
marsh depot
#

ty

slate swan
#

It would probably only work if you make like it like
-choose hello1 hello2

wheat moth
#

@marsh depot what you possibly could do is make it 1 argument
async def choose(ctx, *, opcions=None):

and than command would be like: --choose the first thing to choose of , the second thing to choose of
and by the comma you can split it into 2 args by
opcion1 = opcions.split()[0]
opcion2 = opcions.split()[1]

#

this is the only way of having 2 infinite arguments I think

valid niche
#

they don't track data

slate swan
mighty dust
valid niche
#

intents is literally you as the bot owner telling discord what event data you want to get sent

#

you have all the events

#

and every event is bound to an intent

slate swan
#

If your bot tracks server members or downloads the entire member list, you may need the server members intent to receive member events and the member list.

valid niche
#

if you enable the intent you get the events

#

if you don't enable it you won't get the events

slate swan
#

yeah so the events and list

slate swan
valid niche
#

you could use it to track data...for reasons

#

but intents don't directly track data

slate swan
#

Yeah

#

Ok

slate swan
#

I hate having to type an extra line of code everytime I create a command (await bot.wait_until_ready()), anyway I could make things a bit more easier and not have to type that everytime I create a command?

maiden fable
wheat moth
#

+1

slate swan
maiden fable
#

......?

wheat moth
#

weird

maiden fable
#

Can't really happen tbh bro

slate swan
#

something about the cache not being populated

maiden fable
#

Its an error or something?

slate swan
#

no

maiden fable
#

Then?

slate swan
#

it's the problem, the error is that it simply refuses to get guilds / channels / users without that extra line

maiden fable
#

Well that error generally comes when yr bot is too slow to start

slate swan
#

like it'll return NoneType object

#

instead of returning a guild object

#

or whatever it was told to get

dapper cobalt
#

Can you show your code?

slate swan
#

it's too large

dapper cobalt
#

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

well here's part of it

#
@bot.command(aliases=['ge_addchannel'])
async def guildedit_addchannel(ctx, guild_id, name, type):
  await bot.wait_until_ready()
  if ctx.author.id in dev_access:
    if type.lower() == "text":
      guild = bot.get_guild(guild_id)
      await guild.create_text_channel(name)
      await ctx.send(f"Created a text channel named **{name}** in guild **{guild.name}**")
    elif type.lower() == "voice":
      guild = bot.get_guild(guild_id)
      await guild.create_voice_channel(new)
      await ctx.send(f"Created a text channel named **{name}** in guild **{guild.name}**")
    else:
      await ctx.send("Invalid channel type! Use `devdocs com:guildedit_addchannel` for a list of valid channel types")
  else:
    await ctx.send("You don't have permission to run this command")
#

this command doesn't work without line 2

maiden fable
#

Well yea, understandable

#

That issue generally comes when yr bot starts too slow

#

Cz of low resources/slow net

dapper cobalt
#

Try waiting a little bit before using the command.

maiden fable
#

Isn't that what he's doing....?

dapper cobalt
#

Or, you can use cogs.

slate swan
dapper cobalt
#

Because in that command you are trying to get a guild from the bot's cache.

maiden fable
#

Wait, iirc, dpy uses on_message to check for a message with a command, right?

dapper cobalt
#

Correct.

maiden fable
# dapper cobalt Correct.

Sooo, he can subclass bot and do something like

class MyBot(commands.Bot):
    async def on_message(self, message):
        await self.wait_until_ready() 
        return await super().on_message(message) 

No?

#

That would wait for the bot to be ready before listening for messages? Idk

pliant gulch
#

holy shit finally finished docs for my wrapper

#

I am dying

maiden fable
pliant gulch
#

No I fixed that

#

and the repo hit 100+ commits

#

pog

maiden fable
#

And agreed, making docs is tiring and boring

maiden fable
pliant gulch
#

I need to find someone who will destroy their sleep schedule to write docs for me

#

πŸ˜”

wheat moth
#

I have a question, because if you try to use 2 different commands at the same time bot wiil firstly compute the first command and than the other, can it be optimized by multithreading cogs or anything ?

dapper cobalt
dapper cobalt
#

It's to prevent tasks from blocking each other.

maiden fable
#

My sleep schedule is already fucked up

maiden fable
dapper cobalt
#

I fixed my sleep schedule yesterday since school starts tomorrow.

maiden fable
burnt wharf
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [β€˜@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
dapper cobalt
marsh depot
#

Anyone know how can i make bot send a embed with all the emojis of the guild?

I try

@bot.command()
async def emojis(ctx):
    emojis = bot.get(ctx.guild.emojis)
    await ctx.send(emojis)

But nothing happens

maiden fable
#

!d discord.Guild.emojis

unkempt canyonBOT
marsh depot
#

the same result

maiden fable
#

Wrong person bro

dapper cobalt
maiden fable
dapper cobalt
maiden fable
#

Yea

marsh depot
maiden fable
dapper cobalt
#

@slate swan You can use cogs. They're the best way to prevent most cache issues and also to stay organized.

dapper cobalt
marsh depot
#

and i have this

dapper cobalt
#

What does it log in the terminal?

marsh depot
#
@bot.command()
async def emojis(ctx):
    emojis = ctx.guild.emojis
    await ctx.send(emojis
marsh depot
maiden fable
#

U forgot a )

marsh depot
#

is in the code

dapper cobalt
marsh depot
marsh depot
dapper cobalt
#

Do you have discord.Intents.default()? They include emoji intents.

#

!d discord.Intents.emojis

unkempt canyonBOT
dapper cobalt
#

Try printing emojis instead of sending it.

marsh depot
marsh depot
dapper cobalt
marsh depot
outer violet
dapper cobalt
#

To print the emoji itself, print([f"<:{emoji.name}:{emoji.id}>" for emoji in emojis]).

#

It should work.

dapper cobalt
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.
marsh depot
hasty iron
#

!d discord.Emoji.animated

unkempt canyonBOT
valid niche
#

and we're far from being even done

#

we've got so much to do

pliant gulch
#

get on the grind

valid niche
#

we're with a team btw

pliant gulch
#

I went through a bag of coffee beans

valid niche
#

lol nice

pliant gulch
#

My wrapper is only two people blanket and me

#

πŸ˜” so much 2 do

valid niche
#

very nice

#

what's the name if i may ask?

pliant gulch
valid niche
#

pypi?

pliant gulch
#

Not stable/ready for it

#

Currently only able to download via git

marsh depot
dapper cobalt
#

Now make it send it.

marsh depot
#
@bot.command()
async def emojis(ctx):
    emojis = ctx.guild.emojis
    listaemojis = ([f"<:{emoji.name}:{emoji.id}>" for emoji in emojis])
    print(listaemojis)
    await ctx.send(listaemojis)
slate swan
#

use join

marsh depot
#

ΒΏ?

slate swan
#

await ctx.send(" ".join(emojis))

#

would work

#

I think so atleast

valid niche
slate swan
#

wait, you don't want to send it

#

oof moment

marsh depot
slate swan
#

listaemojis = [f"<:{emoji.name}:{emoji.id}>" for emoji in emojis]

slate swan
#

no, you have brackets

marsh depot
#

i change it lmao

slate swan
#

remove those

marsh depot
slate swan
#

oh okay

#

what does it print?

#

yeah, I know, discord changes it

marsh depot
slate swan
#

so it works?

marsh depot
#

Print this but dont send anything

slate swan
#

remove the ctx.send line?

#

I've just read the whole conversation to understand

#

Im trying to make an app that verifies roblox users, however it is not working.
No error persists, it just ignores this;

        if user == verstr:
            await ctx.send("Verified")```
Full code:
```py
def get_ro_info(x, info):
    user_req = requests.get(f"https://users.roblox.com/v1/users/{x}")
    user_json = user_req.json()
    usr = user_json[info]
    return usr

possible_words = [
    "Happy ",
    "Police ",
    "Gun ",
    "Developer ",
    "Dog ",
    "Squid ",
    "Cat ",
    "Horse ",
    "Cow ",
    "Pig ",
    "Brick ",
    "Pans ",
    "Blocks ",
    "Roblox ",
    "Robloxian "
]

def make_sequence(seq):
    if seq is None:
        return ()
    if isinstance(seq, Sequence) and not isinstance(seq, str):
        return seq
    else:
        return (seq,)

def message_check(channel=None, author=None, content=None, ignore_bot=True, lower=True):
    channel = make_sequence(channel)
    author = make_sequence(author)
    content = make_sequence(content)
    if lower:
        content = tuple(c.lower() for c in content)
    def check(message):
        if ignore_bot and message.author.bot:
            return False
        if channel and message.channel not in channel:
            return False
        if author and message.author not in author:
            return False
        actual_content = message.content.lower() if lower else message.content
        if content and actual_content not in content:
            return False
        return True
    return check

def verifystr(x, y):
    return ''.join(random.choice(y) for z in range(x))

@bot.command()
async def verify(ctx):
    authr = ctx.author
    await authr.send("Please send me your roblox ID:")
    response1 = await bot.wait_for('message', check=message_check(channel=ctx.author.dm_channel))
    verstr = verifystr(10, possible_words)
    await authr.send(f"Please put this in your About Me and DM me `DONE` when done:\n{verstr}")
    response2 = await bot.wait_for('message', check=message_check(channel=ctx.author.dm_channel))
    if response2.content == "DONE":
        user = get_ro_info(int(response1.content), "description")
        if str(user) == str(verstr): # <<< code in question
            await ctx.send("Verified")
        else:
            await ctx.send(f"Not verified {verstr}")
            await ctx.send(response2.content) # Used these messages to look if the strings were the same, and they are.
            await ctx.send(user)```
If you found out why it doesnt work, please mention me!
#

what

#

send an error or something

#

there is none

#

what have you done, what output you got

#

Just the verification sentence, as well as the BIO of the roblox user, which matched

#

verification sentence?

#

sorry, my english isnt super right now as i am sick

#

yeah, its a phrase you have to put in your Roblox bio, which is randomized each time

#

mmhm

#

Whitespace might be the issue, idk

#

so what exactly doesn't work here

#
        if str(user) == str(verstr): # <<< code in question
            await ctx.send("Verified")
        else:
            await ctx.send(f"Not verified {verstr}")
            await ctx.send(response2.content) # Used these messages to look if the strings were the same, and they are.
            await ctx.send(user)```
#

can you print both user and verstr?

#
            await ctx.send(f"Not verified {verstr}")
            await ctx.send(response2.content) # Used these messages to look if the strings were the same, and they are.
            await ctx.send(user)```
slate swan
#
print(verstr)```
before the if statement
#

it looks like the second one has a \n at the end

#

I wouldn't wonder if that would be the issue

#

doesnt print automatically go to the next line

#

idk

#

yes'

#

it does

#

I would check for
if str(user).strip("\n") == str(verstr).strip("\n"):

#

alr

#

nope, doesnt resolve the issue

#

what are those ------

#

from on_ready

#
@client.command()
async def ownercheck(ctx):
  await ctx.send(ctx.guild.owner.mention)```

How is ctx.guild.owner a nonetype here??
#

!d discord.Guild.owner

unkempt canyonBOT
#

property owner: Optional[discord.member.Member]```
The member that owns the guild.
slate swan
#

Making, no sense.

#

intents

#

Do i need intents for this or sum?

#

oh...

slate swan
#

a space at the end for example

slate swan
#

this is not a server that sells bot, make a code and ask for help, we are not going to spoonfeed you

#

hi

i have a command group named whitelist, it shows how to add/remove and the current whitelist
add adds the role to a db,
remove removes it from the db,

i have the EXACT SAME code, but for moderator roles,
add adds the role to a db,
remove removes it from the db,

when i invoke *modroles add @Moderator#8006_role; it works as expected
but when i invoke *nicknamewhitelist add @Nickname#1234whitelist_role; it says role is a missing paramater
i changed the sub command of nicknamewhitelist to add1 and it works as expected
can you not have 2 sub commands in different groups be the same?

covert igloo
# slate swan

How do u request for someone's profile from that api

#

Never seen anyone use the roblox api here

solid wave
#

How do I get the numbers after someones name

#

like instead of

#

Asad

#

its Asad#2831

tawdry perch
#

are you using member obj?

solid wave
#

uh

#

oh no

#

I am making a mute function

#

so !mute Someone

tawdry perch
#

and you take a member obj as a argument, right?

solid wave
#

No

#

I have to use discord.ext

#

for that but it isnt working for me

tawdry perch
#

why can't you use a member obj? It should still work with replit

solid wave
#

I tried

#

it said no such thing as member

tawdry perch
#
async def(ctx, member: discord.Member):
``` did you do smth like that?
solid wave
#

TypeError: on_message() missing 1 required positional argument: 'member'

#

yeah

tawdry perch
#

you use on_message for mute?

solid wave
#

Yeah

tawdry perch
#

are trying to make a antispam?

solid wave
#

No a mute

tawdry perch
#

you are trying to make a command with a event? Why's that?

solid wave
#

I tried to use something like this

@client.command
def mute():
  pass
#

but it didnt work

tawdry perch
#

you need to add arguments

solid wave
#

let me try

#

I use this

#

client = discord.Client()

tawdry perch
#
@client.command
def mute(ctx, member: discord.Member):
  await ctx.send(f"{member} got muted")

``` example to run it `!mute AnyMemberID` or you can mention it (the user)
slate swan
fair zinc
#

how can i IMPORT DISCORD

tawdry perch
#

import discord

slate swan
tawdry perch
#

isn't it pip install discord.py?

fair zinc
#

in powercell?

tawdry perch
#

well anywhere you like to run the pip install

slate swan
#

ig

tawdry perch
#

they are 2 different packages (that should have the same code tho)

slate swan
#

oh

fair zinc
#

it is giving error

solid wave
#

its still not working

slate swan
tawdry perch
fair zinc
#

yeah

slate swan
#

What's ur python version?

solid wave
#

this

fair zinc
#

3.9.6

solid wave
#

TypeError: on_message() missing 1 required positional argument: 'member'

tawdry perch
tawdry perch
solid wave
#

OK

fair zinc
#

same error

tawdry perch
unkempt canyonBOT
#

Hey @solid wave!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

tawdry perch
#

paste it to the link

slate swan
#

here

#

And send the link here

solid wave
tawdry perch
#

remove member: discord.Member at on_message event

solid wave
#

ok

tawdry perch
#

and use @client.command() for commands and not a event

#

thats really bad to use a event for commands

slate swan
#

()

tawdry perch
#

my bad, fixed

slate swan
final iron
#

This code gives me pain

tawdry perch
#

which one?

tawdry perch
#

oh

slate swan
#

All rights reserved. Seriously if you try to copy me I will hack you I know how to do it. And you will never see me coming.

#

what the actual duck

tawdry perch
#

πŸ¦† , this duck

slate swan
#

I hope nobody copies this

final iron
#

@tawdry perch accidentally friended you

#

Don't accept

tawdry perch
#

I was not going to

slate swan
#

why not

#

why not be friends

#

imagine asking someone to be friends and then telling him that you don't want to be

final iron
#

Friends are bad

tawdry perch
#

.topic

lament depotBOT
#
**Do you think there's a way in which Discord could handle bots better?**

Suggest more topics here!

slate swan
#

what is this

tawdry perch
#

a topic

final iron
slate swan
#

true

tawdry perch
#

@solid wave , did you get what was wrong in your code?

slate swan
#

everything

#

it was so everything, you don't even need a thing

#

that's how every it gets

final iron
#

^^^

#

He's gonna have to completely rewrite it

slate swan
#

why this twice

tawdry perch
#

I was just making sure they know what to change

slate swan
#

and on_message doesn't take a member argument

hasty iron
slate swan
#

works as intended for sure

#

person:
!report @slate swan
bot:
reported the heck outta him

tawdry perch
#

discord bots was one of my best projects ever, but sadly everything good ends...

slate swan
#

fool, I'm already making a stickman game in Unity

#

I changed career paths

tawdry perch
#

I made a cube shooter in Unity/3d shooter game (which was worse than you can imagine)

slate swan
#

I'm currently stuck on not being able to play a flipping animation once

final iron
#

I'm pretty sure I could imagine no offense

delicate moat
#

How do I give roles based off role names in a JSON file?
So if I make a JSON like this:

{"866057742989131866": {"722905649360666824": ["@everyone", "staff", "admin", "VIP"]}}

How do i give someone those roles

tawdry perch
slate swan
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
slate swan
#

can i have a commands.cooldown only if a certain thing happens?
i have a command, but if you missspell something after typing the command, it still gives you a cooldown. i want it to only give you a cooldown with an if statement. is that possible?

#

your iterable is gonna be
guildInstance.roles

#

and a name kwarg should take the role's name

tawdry perch
unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

slate swan
tawdry perch
#

np

delicate moat
#

Wait let me try to explain what should happen

slate swan
#

lemme give you an example

delicate moat
#

So I made a command where when you mute someone, it saves their roles in a JSON file, and remvoes all those roles. That works perfectly. but how do i return those roles to the user after you unmute them

slate swan
#
role = discord.utils.get(ctx.guild.roles, name="Admin")
await member.add_roles(role)
slate swan
delicate moat
slate swan
#

well somebody else should be able to help with that

#

definitely not me

#

cuz I don't know nothing about JSON

delicate moat
#

Oh, alright

wheat moth
#

what is your code ?

delicate moat
#
@client.command()
@commands.has_permissions(manage_messages=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json') as f:
        data = json.load(f)
        for role in data["866057742989131866"][member.id]:
          try:
            print(role.name)
            thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
            await member.add_roles(thing)
          except:
            pass
#

I'm definetly doing it wrong

#

I'm not good with JSON files so

final iron
delicate moat
slate swan
#

or manage_members

#

manage_permissions actually

final iron
#

Or manage roles

delicate moat
#

So how would I iterate through the JSON file in this case?

{"866057742989131866": {"722905649360666824": ["@everyone", "staff", "admin", "VIP"]}}
``` ^^ The JSON files looks like this
final iron
#

You wouldn't really want administrator for an unmute command

delicate moat
wheat moth
#

member.id is an integer and you have it as str in json file mb that's the case

#

"722905649360666824"

delicate moat
tawdry perch
#

Ghost ping hyperlemon

slate swan
#

yeah i sent the wrong thing

#

my bad

tawdry perch
#

I cant help atm, I will go to sleep

slate swan
#

oh ok

wheat moth
#

@delicate moat Does it remove 'Muted' role ?

delicate moat
wheat moth
#
      with open('roles.json') as f:
        data = json.load(f)
        for role in data["866057742989131866"][member.id]:
          try:
            print(role.name)
            thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
            await member.add_roles(thing)
          except:
            pass

ok so the problem must be here, gimme sec i'll try to debug it

delicate moat
#

yea, i think the problem is there too

slate swan
#

i have a code in my bot similar to this:

array = [id, id1]

for role in author.roles:
if role.id in array:
do something

it seems as if @ everyone is counted in for role in roles, is there a way to exclude it?

delicate moat
wheat moth
#

I know what happens see when you are reading it those are string and than you want to take name attr from it which string doesn't have
in role.name

#

so you try to do "Admin".name

wheat moth
#

you have to get object of the role from the server by name

delicate moat
boreal ravine
#

add [1:] at member.roles or something

wheat moth
#

but you are printing role.name before that declaration

#

so if you move print down

boreal ravine
#

isnt that how lambda works? idk

slate swan
slate swan
#

?tag slice

#

i saw something abt it but didnt know where

boreal ravine
wheat moth
#

@delicate moat try placing the print(role.name) under thing =

slate swan
# boreal ravine yes

alr bet it works, but if a user has 1 role in array and 1 out, itll send the success message, and then the error message, how do i stop it

slate swan
boreal ravine
#

hm

slate swan
#

like maybe a way to break

#
data = db.find_one({'guild_id': ctx.guild.id})
        modRoles = data['modroles']
        for role in ctx.author.roles[1:]:
            if role.id in modRoles:
                if userdata.find_one({"discord_id": member.id}):
                    epicid = userdata.find_one({'discord_id': member.id})['id']
                    name = userdata.find_one({'discord_id': member.id})['name']
                    embed=discord.Embed(title='Query Successful', description=f'des', color=3145472)
                    await ctx.send(embed=embed)
                    
                else:
                    embed1=discord.Embed(title='Error', description=f'{member} is not linked to an Epic Account', color=16717056)
                    await ctx.send(embed=embed1)

            else:
                embed2=discord.Embed(title='Error', description=f'You need to have a mod role in order to do this command. Administrators of the server can configure mod roles via the `{ctx.prefix}modroles` command.')
                await ctx.send(embed=embed2)```
wheat moth
#

@delicate moat So I think correct code should be:

@client.command()
@commands.has_permissions(manage_messages=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json') as f:
        data = json.load(f)
        for role in data["866057742989131866"][str(member.id)]:
          try:
            thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
            print(role.name)
            await member.add_roles(thing)
          except Exception as err:
            print(err)
delicate moat
#

it prints

'str' object has no attribute 'name'
'str' object has no attribute 'name'
'str' object has no attribute 'name'
'str' object has no attribute 'name'
#

im assuming thats the error right

wheat moth
#

@delicate moat did it work?

delicate moat
#

It still returns the same thing

wheat moth
#

I see, you have to change 'thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)' to 'thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)'

delicate moat
#

It worked!

#

thanks so much :)))

wheat moth
#

k

outer violet
#

what does this mean

wheat moth
#

could you send code ?

outer violet
wheat moth
#

when does this error occur?

lean storm
#

I have installed discord.py but discord is still marked as an error

outer violet
#

when i type something to the bot and when i type back, it also does it for my other server which idk why

wheat moth
#

for both of commands?

outer violet
#

yea

final iron
lean storm
final iron
lean storm
final iron
#

I have a piece of code that will install it into the correct directory

#

Give me a sec

outer violet
#

;~;

wheat moth
#

I'm trying to figure it out because it's quite a lot of code and error that tells me nothing xD

outer violet
#

oh

wheat moth
#

it's @outer violet's issue not mine

outer violet
final iron
#

Also

#

Is that repl?

outer violet
outer violet
final iron
# outer violet yea

You should not use Repl.it to host your bot.

While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:

  • The machines are super underpowered.

    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.

    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.

    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

mortal dove
#

So dumb question but: What is the name of that software you can use to set custom statuses, like playing x for x minutes? I used to have it but lost it in my ocean of downloads.

outer violet
#

i already know that

mortal dove
#

hm ok

#

but I would still like to know the name if anyone else here knows it

outer violet
final iron
#

Nothing im just saying

lean storm
#

but it wont work

final iron
#

Can you import it

lean storm
#

wdym

final iron
#

Can you explain your issue again

lean storm
#

when I type import discord discord is grayed out/underlined

wheat moth
#

@lean storm firstly what IDE are you using?

final iron
#

Reload pycharm

lean storm
#

have

#

4 times

outer violet
lean storm
#

I'm a newbie when it comes to this stuff so don't get angry

wheat moth
#

ok, when you go to file -> settings -> Project: name -> python interpreter , do you see discord

lean storm
#

nope

wheat moth
#

click on + button

#

find it and add it

delicate moat
#

@wheat moth wait why isn't my json dict being deleted?

@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json') as f:
        data = json.load(f)
        for role in data["866057742989131866"][str(member.id)]:
          try:
            thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
            print(thing.name)
            await member.add_roles(thing)
          except Exception as err:
            print(err)
        del data["866057742989131866"][str(member.id)]
#

Like the dictionary with the user id key isn't being deleted for some reason

lean storm
wheat moth
#

@delicate moat you have to do

data["866057742989131866"].remove(str(member.id))
f = open('roles.json', 'w')
json.dump(data, f)
f.close

idk if that is the best way to do that but it works

wheat moth
#

ye

delicate moat
#
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json') as f:
        data = json.load(f)
        for role in data["866057742989131866"][str(member.id)]:
          try:
            thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
            print(thing.name)
            await member.add_roles(thing)
          except Exception as err:
            print(err)
        data = data["866057742989131866"].remove(str(member.id))
        f = open('roles.json', 'w')
        json.dump(data, f)
        f.close()
``` so like this
wheat moth
#

ye

#

and also I'm not sure data["866057742989131866"].remove(str(member.id)) will work because it's dict. Give me sec to check it

delicate moat
#

what if i do

del data["866057742989131866"][str(member.id)]
#

and then do json.dump

wheat moth
#

ye do that

#

@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json', 'w') as f:
        data = json.load(f)
        for role in data["866057742989131866"][str(member.id)]:
          try:
            thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
            print(thing.name)
            await member.add_roles(thing)
          except Exception as err:
            print(err)
          del data["866057742989131866"][str(member.id)]
          json.dump(data, f)

it's more elegant solution to do it i suppose

delicate moat
#

Im pretty sure

del data["866057742989131866"].remove(str(member.id))
``` wont work since its a dict
slate swan
#
@bot.command(aliases = ["lb", "baltop"])
async def leaderboard(ctx,x = 10):
    users = await get_bank_data()
    leader_board = {}
    total = []
    for user in users:
        name = int(user)
        total_amount = users[user]["wallet"]
        leader_board[total_amount] = name
        total.append(total_amount)

    total = sorted(total,reverse=True)    

    em = discord.Embed(title = f"top {x} richest {random.choice(monkeylist)}",color = discord.Color(0xfbff00))
    index = 1
    for amt in total:
        id_ = leader_board[amt]
        member = bot.get_user(id_)
        name = member.name
        em.add_field(name = f"{index}. {name}" , value = f"{amt} banna",  inline = False)
        if index == x:
            break
        else:
            index += 1

    await ctx.send(embed = em)```

why is this happening? it just started giving me this error and I don't know what I did to cause it
wheat moth
#

@delicate moat I fixed it look now

#

@delicate moat because I just copied it blindly instead of changing ;-

#

is it working ?

flint forum
#

Are there any opensource api to use for normal discord.py and not having to convert to slash

#

I have done some searching but I want an opinion from you guys.

final iron
flint forum
wheat moth
#

@slate swan there are 2 reasons this happens, 1: you gave wrong id. 2: You have to fetch user and in this case you can:

member = bot.get_user(id_)
if member is None:
  member = await bot.fetch_user(id_)
flint forum
#

How about none-verified

final iron
final iron
flint forum
#

Oh alr thanks.

final iron
#

If you do end up having to verify you will have to rewrite everything

wheat moth
#

How are those slash commands working bcs I have one verified bot and idk how to convert him to slash commands in case I have to.

kindred epoch
#

you have no theres no in case, unless you get the message content intent

wheat moth
#

So what is the difference between normal commands and slash commands in code?

kindred epoch
#

different stuff

final iron
#

They're pretty similar though

kindred epoch
#

so like instead of ,slap @amber beacon in slash commands it will be something like /slap user:options

delicate moat
kindred epoch
delicate moat
#

Its just a temporary one

#

Ill prolly switch to MongoDb

wheat moth
#

@delicate moat So this works:

@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json', 'w') as f:
        data = json.load(f)
        for role in data["866057742989131866"][str(member.id)]:
          try:
            thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
            print(thing.name)
            await member.add_roles(thing)
          except Exception as err:
            print(err)
          del data["866057742989131866"][str(member.id)]
          json.dump(data, f)
pliant gulch
#

They are very limiting

delicate moat
# wheat moth <@!831391344098017290> So this works: ```py @client.command() @commands.has_perm...
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
  global bot_delete
  if not ctx.author.bot:
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
    if role in member.roles:
      bot_delete = True
      await member.remove_roles(role)
      with open('roles.json') as f:
        data = json.load(f)
        for role in data["866057742989131866"][str(member.id)]:
          try:
            thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
            print(thing.name)
            await member.add_roles(thing)
          except Exception as err:
            print(err)
        del data["866057742989131866"][str(member.id)]
        f = open('roles.json', 'w')
        json.dump(data, f)
        f.close()
      message = await ctx.send("User has been unmuted.")
      embeded = discord.Embed(color = 0xEE8700)
      current_time = datetime.datetime.now(pst).strftime("%H:%M:%S")
      embeded.add_field(name = f"{member} has been unmuted!\n", value=f"{ctx.author} has UNMUTED {member}\n\nDate: {datetime.date.today()}\nTime: {(current_time)} PST\n\nAdmin ID: {str(ctx.author.id)}\nUser ID: {str(member.id)}")
      logs_channel = client.get_channel(896464547588759603)
      await client.wait_until_ready()
      await logs_channel.send(embed = embeded)
    else:
      message = await ctx.send("User isn't muted!")
    await asyncio.sleep(3)
    await message.delete()
    await ctx.message.delete()
    bot_delete = False
wheat moth
#

k

#

I would recommend you to use my method because it opens json file once instead of twice like you do but it is still good.

glad glade
#

Am i able to request a bot if so i would like a bot where only admins and certin people can add money to different members of the discord server

wheat moth
#

could you try to print out list
with print(list) before the 'if len(list) < 0'

#

@potent jetty

#

also you may want to call it list_ because list is also a variable type and they may conflict at some point

#

does it print out anything?

#

before the error

#
@client.command(aliases=['sexy'])
@commands.cooldown(4,15, commands.BucketType.guild)
async def boosters(ctx):
    subscribers = await ctx.guild.premium_subscribers()
    boosters = ""

    if len(subscribers) > 0:
        for i, subscriber in enumerate(subscribers):
            boosters += f"\n`{i}` {subscriber.name}#{subscriber.discriminator}  `({subscriber.id})`"
    embed = discord.Embed(title=f":boost: __boosters__" ,description=boosters ,color=0x2E3235)
    await ctx.send(embed=embed)
#

@potent jetty try using this

#

I changed some variable names so they make sense and may work

#

where is the bot hosted?

#

ye because you get your errors on the chat not in console or anything

#

Could you disable the error handler for sec just comment it out or anything

#

because I would like to know the actual error

#

what is above that

slate swan
#

.premium_subscribers is a property that's why you're getting an error

#

It's not a method which you can call

wheat moth
#

Oh yeah, that's it. I find it quite weird that there was nothing about this line in error msg

#

Although there maybe was something above what he sent

slate swan
#

They indeed are above what he sent as that's not the full error

wheat moth
#

yep, python has like 2 part error.

slate swan
#

Yeah

#

Also it's not a coro so no need to await it, would most likely also raise an error

wheat moth
#

so it'll be:


@client.command(aliases=['sexy'])
@commands.cooldown(4,15, commands.BucketType.guild)
async def boosters(ctx):
    subscribers = ctx.guild.premium_subscribers
    boosters = ""
    for i, subscriber in enumerate(subscribers):
      boosters += f"\n`{i}` {subscriber.name}#{subscriber.discriminator}  `({subscriber.id})`"
    embed = discord.Embed(title=f":boost: __boosters__" ,description=boosters ,color=0x2E3235)
    await ctx.send(embed=embed)
slate swan
#

Yeah

#

Also I'd add i + 1 when concatinating to boosters as the starting point is 0

wheat moth
#

can't you do enumerate(subscribers, 1)
it will start counting at 1

slate swan
#

Yeah you can do that too

wheat moth
#

you could do

@bot.event
async def on_voice_state_update(bot, before, after):
  if before.channel != None and after.channel == None:
    print("BOT VOICE STATE UPDATED")

You check if you've been in channel before and if you are no longer in channel after

#

@slate swan

#

also you shouldn't call first variable 'bot' as it's member not the bot

#

np

#

ye

#

gimme sec i've got to check exactly how

#

in docs

slate swan
#

Use the audit logs

wheat moth
#
@bot.event
async def on_voice_state_update(member, before, after):
  if before.channel != None and after.channel == None:
    if member.id == bot.id:
      print("BOT VOICE STATE UPDATED")
#

this is good for the most part but you have to replace bot.id with id of your bot

slate swan
#

Just do bot.user.id

wheat moth
#

@slate swan

@bot.event
async def on_voice_state_update(member, before, after):
  if before.channel != None and after.channel == None:
    if member.id == bot.user.id:
      print("BOT VOICE STATE UPDATED")
#

yes you can do

try: 
  await guild.voice_client.disconnect(force=True)
except:
  pass
spice moss
#
@client.command()
async def xp(ctx):
    if ctx.author != client.user:
        user_id = ctx.author.id
        mycursor.execute("SELECT xp FROM users WHERE user_id = %s"), [user_id]
        xpdata = mycursor.fetchall()
        await ctx.send(f"Your XP is: {xpdata}")

Why is this command like not working at all? It doesn't send anything, I don't get any errors and nothing like that

wheat moth
#

try putting a print("works")
in between the function declaration and the if statement so you will see if it's called at all

@client.command()
async def xp(ctx):
  print("works")
  if ctx.author != client.user:
    user_id = ctx.author.id
    mycursor.execute("SELECT xp FROM users WHERE user_id = %s"), [user_id]
    xpdata = mycursor.fetchall()
    await ctx.send(f"Your XP is: {xpdata}")
spice moss
#

nope

#

doesnt print

wheat moth
#

are you using cogs ?

spice moss
#

nope

wheat moth
#

could you send me rest of the code ?

#

without the token of course

spice moss
#
import mysql.connector
import discord
from discord.ext import commands


client = commands.Bot(command_prefix="!")
#

thats all without the database part

wheat moth
#
@commands.command()
async def xp(ctx):
  print("works")
  if ctx.author != client.user:
    user_id = ctx.author.id
    mycursor.execute("SELECT xp FROM users WHERE user_id = %s"), [user_id]
    xpdata = mycursor.fetchall()
    await ctx.send(f"Your XP is: {xpdata}")

try this, i just changed client.command to commands.command

spice moss
#

doesnt work

#

either

wheat moth
#

is the bot online when you turn it on and are you writing !xp with all small letters ?

spice moss
#

yes to both of those

#

i have a on_ready event so yea its on

wheat moth
#

do you have any error handler which may hide issue ?

spice moss
#

nope

wheat moth
#

Well, that's an interesting one.

spice moss
#

my on_ready and on_message events work perfectly fine

wheat moth
#

try to comment out all of the database stuff to see if command will run

spice moss
#

thats weird

#

it works without db stuff

wheat moth
#

I don't know a lot about db so you may need to ask someone else to help you with that one

#

but at least you know what causes the problem

slate swan
#
  File "C:\Users\marva\Desktop\sty\main.py", line 42, in <module>
    bot.load_extension(f"cogs.{filename[:-3]}")
  File "C:\Users\marva\python\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\marva\python\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.main' raised an error: AttributeError: module 'discord.ext.commands.cog' has no attribute 'listener'```
#
import random
import discord
import asyncio
import os
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, SelectMenu

import config

bot = commands.Bot(command_prefix="?")
bot.remove_command("help")

@bot.command()
async def load(ctx, extension):
    if ctx.author.id == 888065311289507933:
        bot.load_extension(f"cogs.{extension}")
        await ctx.send("cogs is loaded...")
    else:
        await ctx.send("you are not a bot developer...")


@bot.command()
async def unload(ctx, extension):
    if ctx.author.id == 888065311289507933:
        bot.unload_extension(f"cogs.{extension}")
        await ctx.send("cogs is unloaded...")
    else:
        await ctx.send("you are not a bot developer...")


@bot.command()
async def reload(ctx, extension):
    if ctx.author.id == 888065311289507933:
        bot.unload_extension(f"cogs.{extension}")
        bot.load_extension(f"cogs.{extension}")
        await ctx.send("cogs is reloaded...")
    else:
        await ctx.send("you are not a bot developer...")

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

bot.run(config.TOKEN)```
#
from discord.ext import commands

class user(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.cog.listener()
    async def on_ready(self):
        print(1)

    @commands.command()
    async def info(self, ctx):
        await ctx.send("hello, world!")


def setup(bot):
    bot.add_cog(user(bot))```
slate phoenix
#

it’s commands.Cog.listener()

#

capitalize the C

slate swan
#

thanks

wheat moth
#

and please add py after triple `

#

it's unreadable like this

final iron
wheat moth
#

Ye I know but for the next time.

slate swan
#

This is a python server

celest marlin
#

oop. i copied and pasted to the wrong server, sorry

slate swan
#

It's alr

wheat moth
#

xD

slate swan
#

Happens

#

Β―\_(ツ)_/Β―

wheat moth
#

I imagined going to wrong country by accident, sure someone done that but I would love to see his face the moment he realized.

hearty shoal
#

New to the API, still learning.
Wanting help on how to delete the bot's message via a reaction to that same message.

visual island
halcyon sparrow
#

Is anyone going to change APIs soon?

boreal osprey
#

if you were to add reactions to embeds would it be this?

await message.add_reactions
wispy spade
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Add a reaction to the message.

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

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

welp

vale glen
#

is it because you missed the colons?

#

i dont know though, havent touched dpy in a while

slate phoenix
#

You have to put the unicode like this \βœ… \:white_check_mark:

boreal osprey
#

better example*

vale glen
#

thats a good enough example

slate phoenix
#

you type it out but put a slash before it, then copy it

vale glen
#

ye u can just slot the emoji in

boreal osprey
#

so something like this

#

?

slate phoenix
#

No you have to copy the output that shows up like this: \βœ…

boreal osprey
#

oh

#

\❌

slate phoenix
hearty shoal
#

nvm handled the delete reaction myself

#

it just deletes all of the messages from the bot now because it is defining every sent message instead of the most recent one wahhgone

#

though I could ask for it to delete the message the reaction is on instead of doing that

#

now it's doing it once huehpain

hollow agate
#
    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == 'Warns':
            db = await aiosqlite.connect('database.db')
            cursor = await db.execute('SELECT * FROM warns WHERE user_ids=?', (member.id,))
            rows = await cursor.fetchall()
            await db.close()
            embed = discord.Embed(
                title=f"Warns",
                color=discord.Color.red())
            for row in rows:
                embed.add_field(name=f"Case {row[2]}", value=row[1])
            await interaction.response.send_message(embed=embed)
            return
        if self.values[0] == 'Mutes':
            await interaction.response.send_message(f'Currently Not Available!', ephemeral=True)
        if self.values[0] == 'Bans':
            await interaction.response.send_message(f'Currently Not Available!', ephemeral=True)
        if self.values[0] == 'Kicks':
            await interaction.response.send_message(f'Currently Not Available!', ephemeral=True)

class HistoryView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=5)
        self.add_item(History())

client = PersistentViewBot()
client.remove_command('help')

@client.command()
@commands.has_permissions(administrator=True)
async def history(ctx: commands.Context, member: discord.Member = None):
    if member == None:
        a = await ctx.reply("You can't see the history of nobody!")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await a.delete()
        return
    else:
        view = HistoryView()
        embed = discord.Embed(
            title=f"History of {member}",
            description=
            f"Choose the type of history you would like to view!",
            color=discord.Color.purple())
        embed.set_footer(text="This will time out in 45 seconds from the last interaction.")
        await ctx.channel.send(embed=embed, view=view)
        await ctx.message.delete()
        await view.wait()``` I have this... How can I make it to where in the the tuple in the database, `member.id` works?
slate swan
#

i was just wondering, is this possible to make a spoof process for discord to detect, without using change presense like crearinf a fake minecraft process which actually show minecraft icon on discord??

slate swan
visual island
blazing beacon
#

i think they mean a bot with a game like status such as valorant shows the icon and minecraft shows an icon, i think?

slate swan
hollow agate
slate swan
visual island
#

async def callback(self, interaction: discord.Interaction, member = None): then later put the member to the member parameter

hearty shoal
hollow agate
hearty shoal
#

welp there's no error coming out
wonder where it decided to give up

visual island
slate swan
hollow agate
slate swan
hearty shoal
#

wait_for is the issue here huehpain
even if the reaction is added it just ignores it and proceeds to time out

blazing beacon
slate swan
blazing beacon
#

that name tho rolf

slate swan
blazing beacon
#

.

hollow agate
#

Hmm, can I put a dropdown inside my command somehow?

#

Like defining the dropdown stuff inside of the command instead of using a callback?

hearty shoal
#

can't define ctx in the listener because that breaks the listener entirely (expected)
cannot even use the alternative methods

visual island
hollow agate
visual island
hollow agate
#

What shall I do xD

dapper cobalt
visual island
hollow agate
#

No clue where even it's possible to put it. So I'm not sure :P

hearty shoal
#

is self.bot.wait_for purely a mistake

visual island
hollow agate
#

Could you explain, I'm so sorry, I just don't understand.

visual island
hollow agate
#
@client.command()
@commands.has_permissions(administrator=True)
async def history(ctx: commands.Context, member: discord.Member = None):
    if member == None:
        a = await ctx.reply("You can't see the history of nobody!")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await a.delete()
        return
    else:
        view = HistoryView()
        embed = discord.Embed(
            title=f"History of {member}",
            description=
            f"Choose the type of history you would like to view!",
            color=discord.Color.purple())
        await ctx.channel.send(embed=embed, view=view)
        await ctx.message.delete()
        await view.wait()``` The embed.
hearty shoal
#

nvm ill just ask somewhere else

visual island
dapper cobalt
unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
dapper cobalt
#

What do you mean "a mistake"?