#discord-bots

1 messages · Page 155 of 1

somber sky
#

idk what int is is there a site for that or somethin

sick birch
#

Not in your code - run the command in your terminal

sick birch
mortal pivot
#

How would I go about doing that?

rare echo
sick birch
rare echo
#

but you may have to take it as a str and then convert it because of discords input, i had to anyway

mortal pivot
sick birch
mortal pivot
#

Ah ok

#

Restarted it but it hasnt changed

#

Oh wait I got it

sick birch
#

Yeah it takes a hot second to resolve

mortal pivot
#

I just needed to remove .py. Tyvm for your help it is greatly appreciated ❤️

slate swan
#

anyone here got a big brain idea of how to send a modal if a response has been deferred?

golden portal
safe lintel
#

does anyone know how to make these slash commands instead of prefix commands using nextcord? I was watching a tutorial but it doesnt show how to make them slash commands

shrewd apex
unkempt canyonBOT
mighty pilot
#

can i do a for loop inside a for loop? trying to get recent channel history for every channel in a guild and its giving me a syntax error because i tried doing for every channel do this for every message

naive briar
#

Of course, you can

mighty pilot
#
    messages = [msg async for msg in channel.history(after=seven_days_ago)]
    for message in messages:```
#

its giving me a syntax error on that second for

naive briar
#

The closing ] is missing

mighty pilot
#

its there in the code, i had to retype because its a remote vm and i cant copy paste

disregard, thanks DMseppuku

naive briar
#

🐈

mighty pilot
#

trying to filter out roles for members im looking at in channel history, keep getting the error that User object has no attribute roles. how would i filter out the people that have left in my role sorting since they dont have a member object just user

mighty pilot
#

nvm i used mutual servers

slate swan
#

like changibg it same as dpy to interaction and bot.slash_command

waxen granite
#
                    if mutedRole in user.roles:
                        print(user.roles)
                        await user.remove_roles(mutedRole)
                        embed = discord.Embed(description=f"**Unmuted {user.mention}.\nMute time is now over.**",colour=discord.Colour.green())
                        embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/853533870891859968.png?size=96")
                        await mutechan.send(embed=embed)
                    else:
                        pass
                    self.ezmute[str(guild.id)].pop(userid)
                    self.saveFile(self.ezmute, "moderation.json")
                    return```
whats wrong in this?
slate swan
naive briar
#

Nice variable names

waxen granite
slate swan
waxen granite
#

its a task.event

slate swan
#

this have prob i think

#

other codes are ok

waxen granite
#

well i tried printing every line of the code

#

the codee i shared the first line , its not prnting after it

naive briar
#

What is in the userid var

waxen granite
#
    @tasks.loop(seconds=60)
    async def unmutetime(self):
                unmutetime = mutemsg.created_at + datetime.timedelta(seconds=time)
                x = discord.utils.utcnow()
                if x >= unmutetime:
                  print("this works")
                    mutedRole = discord.utils.get(guild.roles, name="Muted")
                            print ("mutedroles") this also works
                    if mutedRole in user.roles:
                        print(user.roles) this doesnt print

                        print("role+")
                        await user.remove_roles(mutedRole)
                        print("role removed")
                        embed = discord.Embed(description=f"**Unmuted {user.mention}.\nMute time is now over.**",colour=discord.Colour.green())
                        print("before thumb")
                        embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/853533870891859968.png?size=96")
                        print("after thumb")
                        await mutechan.send(embed=embed)
                    else:
                        print("passed")
                        pass
                    self.ezmute[str(guild.id)].pop(userid)
                    print("popped")
                    self.saveFile(self.ezmute, "moderation.json")
                    return
        except KeyError:
            return```
waxen granite
naive briar
#

Eh

slate swan
#

the userid var

waxen granite
#
        for key in self.ezmute.keys():
            guild = self.bot.get_guild(int(key))
        try:
            for key in self.ezmute[str(guild.id)].keys():
                userid = key
                msgid = self.ezmute[str(guild.id)][key]["msgid"]
                chid = self.ezmute[str(guild.id)][key]["chanid"]
                time = self.ezmute[str(guild.id)][key]["timeleft"]
                mutechan = self.bot.get_channel(chid)
                user = guild.get_member(userid) or guild.fetch_member(userid)
                mutemsg = await mutechan.fetch_message(msgid)```
#

fetching it from a json file

slate swan
#

its outside of loop function

#

oh nvm

waxen granite
#

lemme paste it

#

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

waxen granite
#

here the full code

slate swan
#

tried printing key?

#

you're returning on any KeyError within the code, totally not good way of debugging

#
  • json as a database is wack
slate swan
#

thats worse

slate swan
waxen granite
waxen granite
#

okay i guesss its not able to find the user

#

<coroutine object Guild.fetch_member at 0x00000207191F9940>

slate swan
#

it fetched the member object

fallow tree
#

[2022-12-14 13:06:28] [INFO ] discord.client: logging in using static token
[2022-12-14 13:06:29] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 3beb7e716f3e54b6cc7ae2fa050a5ef1).
[2022-12-14 13:06:33] [WARNING ] discord.http: We are being rate limited. PATCH https://discord.com/api/v10/users/@me responded with 429. Retrying in 993.40 seconds.

fallow tree
naive briar
#

You're doing something too fast

slate swan
fast lotus
#

how to do it?

slate swan
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

@fallow tree

fallow tree
#

ye

slate swan
#

check those libraries bottom of the embed

fallow tree
#

checking

slate swan
#

Hello!

I am trying to make a thing where it asks for a value to then it edits a value

Code:

from CONFIG import VALUE

api = input("New value: ")

How would I make it so it edits the value in CONFIG.py? (yes this is for discord bots, just don't know how)

naive briar
#

You mean edit the file or just the value at runtime

slate swan
naive briar
#

And is it have to update the file or just the value at runtime

slate swan
#

Well, that's what I want it to do.

naive briar
slate swan
#

It's in a different file.

loud junco
#

!paste

naive briar
#

Much easier to edit and save

slate swan
loud junco
cloud dawn
#

If you'd create consts I guess.

#

But saving them is only temporary unless you want cursed python code.

terse coyote
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.mute' raised an error: TypeError: unknown parameter given: choices

    @commands.hybrid_command(
        name="mute",
        description="Мутит выбраного участника",
        with_app_command=True
    )
    @app_commands.choices(choices=[
        app_commands.Choice(name="5min", value=5), #value = int(minutes of mute)
        app_commands.Choice(name="30min", value=30),
        app_commands.Choice(name="60min", value=60), #1h
        app_commands.Choice(name="120min", value=120), #2h
        app_commands.Choice(name="1440min", value=1440), #1day
        ])
    @app_commands.choices(choices=[
        app_commands.Choice(name="voice_mute", value=1),
        app_commands.Choice(name="text_mute", value=2)
        ])
    async def mute(
        self, 
        interaction: discord.Interaction,
        member: discord.Member,
        amount: app_commands.Choice[int],
        type: app_commands.Choice[int]
    ):
slate swan
#

I'm using a subcommand, and is it possible to set a custom signature to it that will be displayed using command.signature?

tepid radish
#

Hello, how to make a lot of arguments in command?

maiden fable
tepid radish
#

thanks

upbeat gust
tepid radish
#

import discord

from discord import utils
from discord.ext import commands
from discord.ext.commands import Bot
from time import sleep

bot = Bot(command_prefix=".")
bot.remove_command('help')

@bot.event
async def on_ready():
print(f'{bot.user} is connected!')

@bot.event
async def on_message(message):
await bot.process_commands(message)

@bot.command()
async def hello(ctx):
await ctx.send(f'Привет, {ctx.author.mention}')
@bot.command()
@commands.has_permissions(administrator = True)
async def mute(ctx, member, *, time):
print(member)
print(time)

bot.run("***")

#

whats wrong

naive briar
#

If you don't know what's wrong how can anyone else do

frosty umbra
#

Is there a reason for my discord bot to refuse joining my server 😭

#

Bro just doesn’t want to join

slate swan
#

check if its banned lol

frosty umbra
#

It cant be banned already

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

upbeat gust
#

If not, your dpy is outdated

wintry fable
#

is hikari good for discord bot or should i learn smth else

upbeat gust
#

no one uses hikari

wintry fable
upbeat gust
rugged shadow
wintry fable
#

hmm

#

thanks mate

slate swan
wintry fable
#

Hmm

slate swan
#

i personally have 2 projects running on hikari rn lol

wintry fable
#

I am lit confused

slate swan
#

how experienced are you with python?

wintry fable
#

Not good

#

Just starting

slate swan
#

we'll I'll suggest dpy then, hikari is a bit harder for beginners
you can actually try using both of them for sometime and decide

#

discord.py
or hikari with lightbulb

both are easy for beginners

rare echo
#

i’ve found that you’ll find more support with dpy

slate swan
rare echo
#

yeah their support server seems very

#

aggressive to new users except aggressive isn’t the right word

slate swan
#

in support server of respective libs, hikari is much better than discord.py's

rare echo
#

^

wintry fable
#

There are 2 right

#

Light blub

slate swan
#

lightbulb is an extension for making commands with hikari

wintry fable
#

The another extension for hikari

#

There are 2 right?

slate swan
#

tanjun?

wintry fable
#

Yeah

slate swan
#

there's 3 popular ones

#

lightbulb, tanjun and crescent

loud junco
#

dpy is always the easiest

wintry fable
#

Hmm

slate swan
#

lightbulb is old and easy
tanjun is way too advanced
crescent is easiest thing to exist

loud junco
#

what is these 3

#

nvr heard of them before

slate swan
#

crescent only supports app commands tho

loud junco
#

extension?

wintry fable
#

Yeah

slate swan
unkempt canyonBOT
wintry fable
#

Ig

loud junco
#

i sea

slate swan
#

!pip hikari-tanjun

unkempt canyonBOT
wintry fable
#

I am going with hikari

loud junco
#

have fun :D

wintry fable
#

Which one should I go with tanjun or lightbulb

lyric sandal
#

I'm getting this error using slash commands with autocomplete (nextcord), but theres no useful traceback. How can I fix it?

slate swan
# wintry fable I am going with hikari

feel free to ping me if you face any issues related to it, or just use their help server if you ain't able to find quick help here (.gg/hikari is the vanity)

loud junco
slate swan
wintry fable
slate swan
#

tanjun makes you create a seperate handler client for commands and makes you do things manually, with a high reliability on dependency injection
lightbulb is simple, subclasses the main bot class for command handler and has easy interface

tough lance
#

My bot is verified and I don't really want to request message content. I know that you can get message content whenever someone mentions the bot. Does it also work when someone replies the bot with @ ON

shrewd fjord
slate swan
#

@tough lance yep

cloud dawn
shrewd fjord
tough lance
#

I just checked, there isn't any option to turn ping on or off while replying to a bot.

shrewd fjord
#

the acc is just new xd

cloud dawn
shrewd fjord
#

shit ig i forgot to use emojis 🙂

shrewd fjord
#

!e asdd

slate swan
shrewd fjord
#

lol

#

there is

slate swan
#

there definitely is

shrewd fjord
tough lance
#

No option on discord desktop Client

shrewd fjord
#

wait no

#

nvm

tough lance
#

it isn't its just highlighted

shrewd fjord
#

wait imma check real quick

#

ok confirmed, there is no @ option while replying to a "app command"

slate swan
shrewd fjord
tough lance
shrewd fjord
#

i also too thought it's ephemeral

tough lance
#

There isn't any dismiss message option

slate swan
tough lance
#

!topic

shrewd fjord
#

...

tough lance
#

Its working in this server but not in the testing server

shrewd fjord
#

it's prefix command, so.. u can do it

#

prefix command

tough lance
#

oh, now everything is clear

shrewd fjord
tough lance
#

Thanks

#

Anyway back to the main question.

shrewd fjord
#

with slashcommands:

tough lance
#

How actually do I get the content when someone replies. I'm using disnake.

slate swan
#

just like you would do normally

#

message.content

tough lance
#

I mean how to catch it

shrewd fjord
#

check docs

slate swan
#

!d discord.Message.reference will not be None

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

shrewd fjord
#

ye refrence works

#

!d disnake.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

shrewd fjord
#

nice exists

tough lance
#

oh thanks now I can try it.

slate swan
#

new in 1.5

#

its like 2 yrs old so ofc all forks will have it too

shrewd fjord
#

who knows if they changed that to lil bit xd

tough lance
#

Just checked, it works

slate swan
#

guys I need help asap

#

I have a discord predictor bot for blox flip and rblx wild but I want to make it in an app like a app where u can use the predictor.

rare echo
#

huh

raw quail
#

Hello guys

#

Is it possible to implement a function to delete it, if the title of the embed message written in the channel is the same as the title in the newly sent embed message ??

abstract onyx
#

anyone got open source discord bot project. I just need example to better understand discord.py

unkempt canyonBOT
#

Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!

Projects to Contribute to
Sir Lancebot - our fun, beginner-friendly bot
Python - our utility & moderation bot
Site - resources, guides, and more

Where to start

  1. Read our contribution guide
  2. Chat with us in #dev-contrib if you're ready to jump in or have any questions
  3. Open an issue or ask to be assigned to an issue to work on
abstract onyx
#

do I need to know about OOP before starting discord py ?

velvet compass
#

It certainly helps, as well as knowing the basics of async

slate swan
#

its recommended to know the basics
atleast things like the difference between a class instance and a type

abstract onyx
#

isn't it OOP ?

slate swan
#

indeed it is, everything in python is Object oriented

abstract onyx
timber kindle
#

what's the discord.py attribute for a user's avatar?

naive briar
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
velvet compass
#

What are you testing?

wet kelp
#

Nothing

unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

bright wedge
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/latest/api.html#discord.Message "discord.Message") from the destination.
bright wedge
#

You figure out?

jagged sand
#

Hey guys I had a question regarding discord.py button

#

how can i make a command repeat itself by pressing the button

#

i got all the stuff sorted but the button is a pain in the 😐

#

i want to send a new meme when the button is pressed

shrewd apex
#

wth interaction=discord.Interaction

jagged sand
#

it means what it says moyai

shrewd apex
jagged sand
#

its in the official repo so ye

shrewd apex
jagged sand
#

we later use it to callback

shrewd apex
#

what u need is a typehint interaction: discord.Interaction

jagged sand
#

hmm

#

how can i run the cmd again tho

alpine oar
#

yo i need help rq

full marten
#

How can i edit a slash message?

alpine oar
#

i try to run the code but it just says no moduled named discord

#

even tho i have already installed discord and stuff

full marten
#

But doesn't works

upbeat otter
full marten
#

My code:

    @app_commands.command(name='ping', description="Shows the bot's latency in ms.")
    async def ping(self, interaction: discord.Interaction):
        """ use /ping for ping command"""
        latency = round(self.bot.latency * 1000)
        message = await interaction.response.send_message(f'🏓 Pong!\n...', ephemeral=False)
        await asyncio.sleep(0.3)
        await message.edit(content=f'\n{latency}ms ') # Here doens't works
full marten
upbeat otter
full marten
upbeat otter
unkempt canyonBOT
#

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

Edits the original interaction response message.

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

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

You helped a lot

upbeat otter
#

hm

alpine oar
#

it doesnt even make the discord colored

#

i am just so fricking tired lul

upbeat otter
#

is the python version in vscode the same as in which you installed dpy?

alpine oar
#

i think soo

#

yes it is

#

should i test the pip install thing?

upbeat otter
#

yeah ofc

limpid hemlock
#

Did anyone of you played around with ChatGPT? Like integrated it into a Discord Bot?

alpine oar
upbeat otter
#

cool

alpine oar
#

does anyone know how to make an bot purge meassegeas

#

?

upbeat otter
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
upbeat otter
#

grab a text channel object and use the purge method on it

#
channel = bot.get_channel(channel_id)
await channel.purge(limit=100)
alpine oar
#

wait wahtttt

alpine oar
alpine oar
#

oh

#

so i just copy paste thhat?

alpine oar
#

i think i need to add ehh like the 'purge' thingy

upbeat otter
alpine oar
upbeat otter
#

yes

alpine oar
#

whats that

upbeat otter
#
@bot.command()
async def purge(ctx: commands.Context, limit: int) -> None:
  await ctx.channel.purge(limit = limit)

🛐 here you go

naive briar
#

Good job

alpine oar
#

......... well sorry i just dont know what spoonfeed means

#

well ty anyways

alpine oar
peak pewter
#

On

@client.event
async def on_member_join(member):
    welcomeRole = discord.utils.get(guild.roles, name = "Welcome")
    await member.add_roles(welcomeRole)

guild.roles is not defind

regal cove
#

how do you reset synced commands?

regal cove
full marten
#

Do you have?

#

or you know how to make

regal cove
shrewd fjord
#

Huh?

drifting arrow
#

I remember a while ago that someone wanted to create dual !command and /command where the command is the same, how do I do that?

#

for example: !help and /help

naive briar
#

!d discord.ext.commands.Bot.hybrid_command

unkempt canyonBOT
#

@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
drifting arrow
#

Ty ty

peak pewter
#
@client.event
async def on_member_join(member):
    welcomeRole = discord.utils.get(member.guild.roles, name = "Member")
    await member.add_roles(welcomeRole)

if I want this also to send a message of welcome in the welcome channel what should I add?

fading marlin
#

you're not responding in time. You only have 3 seconds to respond to an interaction

cold sonnet
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
shrewd fjord
#

Top of the call back

cold sonnet
#

ctx?

shrewd fjord
#

ctx.response.defer()

cold sonnet
#

ah

shrewd fjord
regal cove
#

how do you make a slash command admin only?

shrewd fjord
#

@app_commands.checks.has_permissions(administrator=True)

regal cove
shrewd fjord
#

U know better where completing tasks taking long

#

Where u need to do something long, then defer it before that task

drifting arrow
#

How do I check if a message is sent to DM?
I cant to setup a system so when someone uses a command, the bot opens up chat with the user in DMs and asks them various questions.

shrewd fjord
#

Yes do it

shrewd fjord
drifting arrow
#

lol

#

Trying to think of a good way to handle this stuff

#

Yes please

shrewd fjord
#

Fk forgot the argument

#

Ye

#

Full code... Or
..

drifting arrow
#

uhh

shrewd fjord
#

!d discord.DMChannel

unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
shrewd fjord
#

Oh yeah @drifting arrow

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.

drifting arrow
#

What Database system you working with?

shrewd fjord
#

check
if isinstance(message.channel, discord.DMChannel):

drifting arrow
#

oh

#

try the async version

#

that'd improve performance

ember nest
#

Bruh man every time I try to play / stop / skip music bot it's just not working at all

drifting arrow
#

In regards to the query, you need to ensure {ctx.guild.id} is the same type as serverID in your database

drifting arrow
#

Just do a simple print? print(type{ctx.guild.id}

shrewd fjord
#

also u didnt f string so it not gonna return guild id

drifting arrow
#

or if you dont care either way, do guildid = int(ctx.guild.id) or guildid = str(ctx.guild.id)

shrewd fjord
#

!e
e=[]
print(type(e))

unkempt canyonBOT
#

@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.

<class 'list'>
drifting arrow
#

Coz if you dont match data types you'll get an error

#

lol this is evil

shrewd fjord
#

Ok u did pretty gud thing

#

WHAT THE HECK IS RESULT IF U DIDN'T EVEN declared

#

well not being rude xd

drifting arrow
#

anyway love to stay and help but i got a discord bot to write! 😄

shrewd fjord
#

result=cursor.execute(...)
@slate swan

ember nest
#

You know how to make bot playing music / stop / skip / stop / resume (just with song name) ? @shrewd fjord

shrewd fjord
#

Fix it or 🔫

ember nest
shrewd fjord
#

...

shrewd fjord
ember nest
#

Alright no problem

shrewd fjord
#

Oh nvm

#

I am being dumb 😂

#

@slate swan is it pycord???

#

Ok dawg

#

Wait no

#

Pycord's module name also as discord

#

Fk me being dumb today

drifting arrow
#

How do I make my discord bot wait for message response?

shrewd fjord
#

Hm?

drifting arrow
#

Like say my bot dms a user and asks "What color would you like your role to be?"
how do I make it wait for a response?

shrewd fjord
#

!d discord.Client.wait_for

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.11)"). 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.11)") 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.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
shrewd fjord
#

@drifting arrow

drifting arrow
#

Ty ty

#

Can I use waitfor in slash commands?

shrewd fjord
#

When a member dm a bot

#

Bot asks some ques right?

#

Then how's that related to slash

drifting arrow
#

okay

#

Coz I want the user to do something like /changecolor then the bot dms the user "What color?"
and then waits for them to reply

#

lol

#

Im exploring all new territory here and I ran out of coffee

shrewd fjord
#

/changecolor [give a color parameter] it's so simple using slashcommand

#

🤷

drifting arrow
#

I want the bot to have other things

#

This is all an example

shrewd fjord
#

I c

drifting arrow
#

I'll expand upon it to have other questions lol

shrewd fjord
#

Well it's possible

#

Idk anything about db so don't ask me

#

Asking me = 🔫

#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
shrewd fjord
#

Ok makes sense

#

@slate swan here u made a gud mistake

#

!d discord.Guild.icon

unkempt canyonBOT
shrewd fjord
#

@slate swan

#

embed=....
embed.set_thumbnail(...)

brisk dome
#

is there any way to change the bots prefix (using text commands) 'live' e.g. while it is still running?

#

such as .set-prefix > and now it uses > as the prefix, so >ping

white citrus
#

the time is wrong

#
        now = datetime.utcnow()
        
        time = datetime.fromtimestamp(min(int((datetime.now() + timedelta(days=28)).timestamp()),int((now + timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).timestamp())))
slate swan
#

what are u trying to do ?

#

whats the issue?

#

yea idk what ur code is doing

#

why would roles be an empty string?

#

why not use a list

ember nest
#

Does anyone know how to make a music bot because I don't know at all and need to learn how to

white citrus
rare echo
#

maybe they were attempting “if roles:” so you could handle if there were none? idk looks odd

full marten
#

It would be like this for editing original response?

#
    @app_commands.command(name='ping', description="Shows the bot's latency in ms.")
    async def ping(self, interaction: discord.Interaction):
        """ use /ping for ping command"""
        latency = round(self.bot.latency * 1000)
        message = await interaction.response.send_message(f'🏓 Pong!\n...', ephemeral=False)
        await message.edit_original_response(content=f'\n{latency}ms ')
#

That didn't work

fading marlin
#

send_message doesn't return anything. You have to use Interaction.edit_original_response

#

though at that point simply add latency to the actual response?

slate swan
#

an additional way.

await inter.response.send()
msg = await inter.original_response()
await msg.edit()
full marten
#

Thank you even so

full marten
slate swan
#

?

full marten
#

like that

full marten
#
    @app_commands.command(name='ping', description="Shows the bot's latency in ms.")
    async def ping(self, interaction: discord.Interaction):
        """ Use /ping for ping command"""
        latency = round(self.bot.latency * 1000)
        await interaction.response.send_message(f'🏓 Pong!\n...', ephemeral=False)
        await asyncio.sleep(0.3) # Here
        await interaction.edit_original_response(content=f'🏓 Pong!\n{latency}ms ')
slate swan
#

why lmfao

full marten
fading marlin
#

why aren't you sending the latency directly?

slate swan
#

also ephemeral is defaulted to False no need to define it

full marten
#

i'm testing many things

#

@fading marlin

fast lotus
tiny grail
#


@client.command()
async def cls(ctx, amount: int):
    if ctx.author.guild_permissions.manage_messages:
        deleted = await ctx.channel.purge(limit=amount + 1)

        await ctx.send(f"Messages Purged: {len(deleted) - 1}")```

When used, it does send the messages purged message, but there's a few seconds of delay before it does. The bot has a typical latency of 45 ms so that's not the issue
fading marlin
#

probably because purging might take some time?

tiny grail
#

It's been a while since I've messed with bots, but I've had another one a long while back, it was instant, the message. I love the sarcasm, but maybe tone it down?

night crater
#

I mean the simplest way to find out is to just time the methods

tiny grail
fading marlin
#

excuse you?

night crater
#

🤨

cold sonnet
#

where did rawreactionactionevent.reaction go

slate swan
cold sonnet
slate swan
#

how can i use this variable result or whatever, in another embed.

slate swan
dusk girder
alpine cove
#

preferably a database

slate swan
fading marlin
#

you can store it as a simple instance attribute

alpine cove
alpine cove
slate swan
#

like in the picture

fading marlin
alpine cove
#

use a dictionary or smth

slate swan
#

what about global variables

alpine cove
#

bruh

alpine cove
#

I have no idea what ur talking about

#

attr of the command?

sturdy owl
#

Hi guys, just opened an help thread about loops not working, maybe someone here could have a look and point me in the right direction, thanks for your time =)

fading marlin
# alpine cove give me an exmaple

they're in a view, and they need to pass the value of one thing inside the callback of a button to another button. What's convenient is that both button callbacks are methods of the same view

class A:
  def __init__(self):
    self.value: str | None = None

  def first(self, value: str) -> None:
    self.value = value
    print(f"Value has been set to {value}")

  def second(self) -> None:
    print(f"Value is currently set to {self.value}")

>>> a = A()
>>> a.second()
Value is currently set to None
>>> a.first("foo")
Value has been set to foo
>>> a.second()
Value is currently set to foo
alpine cove
#

ok well thats just class attributes

#

i dont get how u r gonna use this in d.py?

slate swan
#
        msg = await interaction.client.wait_for("message", check=lambda m: m.author == interaction.user and m.content.isdigit())
        x = (f"{int(msg.content)*0.0025}$") 
        embed = discord.Embed(title="Purchase Confirmation", description="", color=0xF1C40F)
        embed.add_field(name="Purchase Quantity :", value=msg.content, inline=False)
        embed.add_field(name="Price :", value=" ``" + x + "``", inline=False)
        await interaction.channel.send(embed=embed, view=a()) 
        await interaction.message.delete()```
#

can someone help?

fading marlin
fading marlin
fading marlin
slate swan
#

i have extreme skill issue)

fading marlin
#

where the class A is your view, and first and second your buttons

slate swan
#

would you be kindly enough to write me how it would look like 😭

fading marlin
#

no, I'm not going to spoon feed you. I can guide you through it though

slate swan
fading marlin
alpine cove
#

not two buttons

fast musk
#

Have the view track the state and reference from instance variables on the view

#

In a button, self.view.foo = "bar"

#

This is where it breaks away largely from "discord bots" to just normal python programming and design

#

a ui.View is just like any other object that you can extend

sturdy owl
#

Hi guys, is anybody here who could help me with a problem regarding loops? sent my code in #1052692833292796004

fast musk
#

sent a response

full marten
limpid otter
#

how it is possible to make request in a database outside of functions? (in cogs)

slate swan
#

Can you elaborate more

safe lintel
somber sky
bright wedge
somber sky
#

yea if you want

#

it will help

somber sky
slate swan
#

@client.tree.command(name='giveaway', description='Starts a giveaway')
async def giveaway(ctx: discord.Interaction):
  await ctx.response.send_message("Let's start with this giveaway! Answer these questions within 15 seconds!")
  questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
  answers = []
  def check(m):
    return m.author.id == ctx.user.id and m.channel.id == ctx.channel.id
  for i in questions:
    await ctx.channel.send(i)
    try:
      msg = await client.wait_for('messsage', timeout=15.0, check=check)
    except asyncio.TimeoutError:
      await ctx.channel.send('You didn\'t answer in time, please be quicker next time!')
      return
    else: 
      answers.append(msg.content)
  try:
    c_id = int(answers[0][2:-1])
  except:
    await ctx.send_message(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
    return
  channel = client.get_channel(c_id)
  time = convert(answers[1])
  if time == -1:
    await ctx.channel.send("You didn't answer with a proper unit. Use (s|m|h|d) next time!")
    return
  elif time == -2:
    await ctx.response.send_message("The time just be an integer. Please enter an integer next time.")
    return  
  prize = answers[2]
  await ctx.channel.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
  embed = discord.embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
  embed.add_field(name = "Hosted by:", value = ctx.author.mention)
  embed.set_footer(text = f"Ends {answers[1]} from now!")
  my_msg = await channel.send(embed = embed)
  await my_msg.add_reaction("🎉")
  await asyncio.sleep(time)


#

why is it saying I didnt answer in time

somber sky
#

how would I make a giverole command but where you can only give certain roles that are in a list if that makes sense

#

ik i could just do an eaasy variable but its 30+ roles

#

im trying to figure out how to make it shorter

#

im going to try to explaain the best I can. Pretty much this is a football sign bot. I want to make it where whatever team role you have, when you run the command, it gives the person you mentioned the team role that you have. Example im on team 1. I try to sign someone, it will automatically give them the team 1 role. But the thing that is hard is that there are 32 teams. So I can't just do 32 if statements.

bright wedge
somber sky
#

yea

slate swan
#

@somber sky you can just do

if FORole or GMRole or HCRole in ctx.author.roles:
  await ctx.send("I have the roles!")
else:
  await ctx.send("I dont have roles!")
somber sky
#

i tried that

#

idk why it didnt work

slate swan
#

invite me

#

I want in on this bot, sounds interesting (if you dont mind)

somber sky
#

lol

#

the elif stuff works

#

alr check dms

slate swan
#

alr thanks

fading marlin
#

you would probably be looking for any in this case

bright wedge
somber sky
#

nah lol

slate swan
#

max is 25 but you can do some tricks to allow more based on type matching

slate swan
# somber sky nah lol

using autocomplete will remove the thousands of if statements you would be writting

#

@sick birch

#

we got a weirdo in here

fading marlin
#

noo don't make them take our image perms too!!

primal token
sick birch
#

<@&831776746206265384>

#

yeah i cant do much but proxy to the mods

visual yarrow
#

!mute 1052634780937748570 spam

slate swan
#

ahhh

unkempt canyonBOT
#

:x: According to my records, this user already has a mute infraction. See infraction #83973.

rancid grail
#

!mute 1052634780937748570 incident_investigating

unkempt canyonBOT
#

:x: According to my records, this user already has a mute infraction. See infraction #83973.

slate swan
#

noice thanks

visual yarrow
#

(literally spam)

primal token
#

I love spam

slate swan
#
troll = '<:trollface_left: 998951318133673984>'
@client.tree.command(name='test', description='custom image embed')
async def emb(ctx: discord.Interaction):
  await ctx.response.send_message(f'{troll}')
#

why wont custom emojis work?

vagrant brook
#

the actual format of custom emoji is <:name:id> i think

slate swan
#

thats what I have

vagrant brook
#

ok you just edited it

slate swan
#

yea

vagrant brook
#

make sure the id is correct then

#

looks good to me

hollow sparrow
#

Can someone help me understand why when I try to run my discord bot in my priv server it don't wanna actually function and respond with an answer?
heres the code import discord

client = discord.Client()

@client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == client.user:
return
def is_food(word):
KNOWN_FOODS = ["apple", "banana", "carrot", "pizza", "chocolate", "strawberry", "broccoli", "chicken", "beef", "fish"]
return word in KNOWN_FOODS
# Check if the message contains the word "food"
if "food" in message.content.lower():
# Check if the word is a known food or not
if is_food(message.content):
general_channel= client.get_channel(872336555182800948)
await message.channel.send("That's a real food!")
else:
await message.channel.send("I don't think that's a real food.")
I have the client.run and the token for the bot

vagrant brook
#

you need message intents on

vagrant brook
#

you are using a very outdated tutorial

hollow sparrow
slate swan
slate swan
fading marlin
#

"blocked"?

slate swan
#

:cat_sip:

#

:cat_sip:
vagrant brook
slate swan
#

auto fixes itself

vagrant brook
#

wut

slate swan
#

:cat_sip:

fading marlin
#

add a backspace before instead?

slate swan
#

:cat_sip:

vagrant brook
#

make sure you got the emoji id, not the message id

slate swan
#

sent this in the server to get the id

#

without the id

fading marlin
#

I've got no clue what you're trying to do

slate swan
#

trying to send custom emoji but it just sends the name

fading marlin
#

because there's a space

#

<:trollface_left: 998951318133673984>

slate swan
#

no

#

I explained why I put a space there

#

theres no space in my code

vagrant brook
slate swan
#

if I dont put a space it deletes the message

vagrant brook
#

maybe its this

fading marlin
vagrant brook
#

weird then

slate swan
#

its a public server

#

no bruh

slate swan
#

thats why I put A SPACE in what I sent SO it DOESNT DELETE

fading marlin
#

oh

#

I misunderstood, sorry

vagrant brook
#

i cant see the space smh

#

mobile moment

slate swan
hollow sparrow
fading marlin
#

I still don't get what happens when your bot sends the message though?

slate swan
#

it doesnt send the custom emoji

#

it just sends the emoji name

#

@client.tree.command(name='test', description='custom image embed')
async def emb(ctx: discord.Interaction):
  await ctx.response.send_message(troll)
hollow sparrow
fading marlin
#

is the emoji from the same server?

slate swan
#

no

fading marlin
#

does your bot have permissions to use external emoji?

vagrant brook
#

and is the bot in the server which has the emote

vagrant brook
slate swan
#
  File "main.py", line 33
    await ctx.channel.send(f"Signed {user.mention!}")
                           ^
SyntaxError: f-string: invalid conversion character: expected 's', 'r', or 'a'
    await ctx.channel.send(f"Signed {user.mention!}")
hollow sparrow
#

import discord
intents = discord.Intents(messages=True)

client = discord.Client()

@client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == client.user:
return
def is_food(word):
KNOWN_FOODS = ["apple", "banana", "carrot", "pizza", "chocolate", "strawberry", "broccoli", "chicken", "beef", "fish"]
return word in KNOWN_FOODS
# Check if the message contains the word "food"
if "food" in message.content.lower():
# Check if the word is a known food or not
if is_food(message.content):
general_channel= client.get_channel(872336555182800948)
await message.channel.send("That's a real food!")
else:
await message.channel.send("I don't think that's a real food.")

client.run(removed for obvious reasons)

#

@vagrant brook

fading marlin
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

fading marlin
slate swan
#

oh

#

thanks```py
@client.tree.command(name='sign',description='Sign a player.')
@app_commands.describe(user = 'pick a user')
async def sign(ctx: discord.Interaction, user: discord.Member):
FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
if FORole or GMRole or HCRole in ctx.author.roles:
await ctx.channel.send(f'Signed {user.mention}!')
if user.id != ctx.user.id:
name = list(nflRoleListNames)
roles = list(ctx.user.roles)
for name in roles:
if name == roles:
FORole = discord.utils.get(ctx.guild.roles, name=name)
await user.add_roles(role=name)
else:
await ctx.channel.send("You are not a coach.", hidden=True)

Trying to make it so that when you sign someone, it will give them the role that you have
#

I get no errors but it doesnt work

fading marlin
#

this

if FORole or GMRole or HCRole in ctx.author.roles:

is evaluated as

if (FORole) or (GMRole) or (HCRole in ctx.author.roles):

you'd probably be looking for something like this

if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

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

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
fading marlin
#

add_roles doesn't have a role kwarg either 🤔

somber sky
#

no errors

fading marlin
#

you should probably be getting errors. Do you have an error handler that might be eating them up?

slate swan
#

I dont have any

somber sky
#

were both working on different projects and we both dont get errors

fading marlin
#

well, I've mentioned above a few things that might be causing issues

somber sky
#

this is what i have

#
@slash.slash(description='Sign a player.')
async def sign(ctx, user: discord.Member):
  FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
  GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
  HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
  if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
    await ctx.send("I have a role or more")
    if user.id != ctx.author.id:
      for role in nflRoleListNames:
        if role in ctx.author.roles:
          await user.add_roles(role=role.id)
  else:
    await ctx.send(f"You are not a coach.", hidden=True)
    print("User was not a coach.")```
slate swan
#

@fading marlin used those methods, they dont work, no errors

somber sky
#

i have a feeling its the list

#

idk why

slate swan
#
  if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
    await ctx.channel.send(f'Signed {user.mention}!')
    if user.id != ctx.user.id:
        name = list(nflRoleListNames)
        roles = list(ctx.user.roles)
        for name in roles:   
          if name == roles:
            name = discord.utils.get(ctx.guild.roles, name=name)
            await user.add_roles(name)
fading marlin
#

Interaction.user.roles already returns a list, so I don't see why you're casting it to a list. Additionally, you're comparing Role to a list... which will always be false

slate swan
#

if it returns a list, then why wont it work?

fading marlin
#

you're overriding name

name = list(nflRoleListNames)  # list of something
roles = list(ctx.user.roles)  # list of roles
    for name in roles:  # name is now a Role object
        if name == roles:  # comparing (Role == list[Role]) which is always false
hollow sparrow
#

ok, update

#

if "food" in message.content.lower():
# Check if the word is a known food or not
if is_food(message.content):
general_channel= client.get_channel(872336555182800948)
await message.channel.send("That's a real food!")
else:
await message.channel.send("I don't think that's a real food.") This part is what is screwing me up. how could I fix this.

#

I need KNOWN_FOODS = ["apple", "banana", "carrot", "pizza", "chocolate", "strawberry", "broccoli", "chicken", "beef", "fish"]
return word in KNOWN_FOODS to be a thing that when people type in any of these, it will either respond with either say yes its real or no its not a real food.

slate swan
#

for name in list(roles)

hollow sparrow
#

so would it be for example for KNOWN_FOODS in message content lower

fading marlin
#

you want to check if a message contains any words given in a list?

hollow sparrow
#

yes

hollow sparrow
#

Apparently how it was initially It was looking for just the word food and it would always say, no its fake food.

bright wedge
#

if you want help

somber sky
#

you can now @bright wedge

bright wedge
#

!pip aiosqlite

unkempt canyonBOT
slate swan
#

and for the bot role

#
  if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
      roles = list(nflRoleListNames)
      if ctx.user.roles in roles:
        await ctx.response.send_message(f'found {roles}')
      else:
        await ctx.response.send_message(f"not found {roles}")
#

why is it saying not found

fading marlin
#

you're checking if a list is inside a list

slate swan
#

how can I check if the authors roles is in the list of names

fading marlin
#

should they have all of the roles in nflRoleListNames or just one?

slate swan
#

one

fading marlin
#

use the same expression you have above in your if-statement

slate swan
#

?

fading marlin
#

any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles) but change the hardcoded list of roles to the nflRoleList one

slate swan
#

place that under the if statement or replace it

fading marlin
#

you change it with the if statement that's checking if a list is inside a list

slate swan
#

what is ctx.user

fading marlin
#

a badly named parameter. ctx is the injected Interaction

slate swan
#
      roles = list(nflRoleListNames)
      if any(role in [nflRoleListNames] for role in (ctx.user.roles)): 
        await ctx.response.send_message(f'found {roles}')
      else:
        await ctx.response.send_message(f"not found {roles}")
fading marlin
slate swan
#

ok I see

#

still not found

fading marlin
#

send your updated code please

slate swan
#
  if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
      if any(role in nflRoleListNames for role in (ctx.user.roles)): 
        await ctx.response.send_message('found')
      else:
        await ctx.response.send_message("not found")
  else:
    await ctx.channel.send("You are not a coach.", hidden=True)
fading marlin
#

the full callback

slate swan
#

like full code

#
@client.tree.command(name='sign',description='Sign a player.')
@app_commands.describe(user = 'pick a user')
async def sign(ctx: discord.Interaction, user: discord.Member):
  FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
  GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
  HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
  if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
      if any(role in nflRoleListNames for role in ctx.user.roles): 
        await ctx.response.send_message('found')
      else:
        await ctx.response.send_message("not found")
  else:
    await ctx.channel.send("You are not a coach.", hidden=True)
fading marlin
#

what exactly is nflRoleListNames?

slate swan
#
nflRoleListNames = ["Arizona Cardinals", "Baltimore Ravens", "Atlanta Falcons", "Buffalo Bills", "Carolina Panthers", "Cincinnati Bengals", "Chicago Bears", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Houston Texans", "Green Bay Packers", "Indianapolis Colts", "Los Angeles Rams", "Jacksonville Jaguars", "Minnesota Vikings", "Kansas City Chiefs", "New Orleans Saints", "Las Vegas Raiders", "New York Giants", "Los Angeles Chargers", "Philadelphia Eagles", "Miami Dolphins", "San Francisco 49ers", "New England Patriots", "Seattle Seahawks", "New York Jets", "Tampa Bay Buccaneers", "Pittsburgh Steelers", "Washington Commanders", "Tennessee Titans"]
fading marlin
#

oh, then you have to get the name of the role on your second if-any stmt

slate swan
#

how? im confused

fading marlin
#

role is an instance of Role, and Role has a name attribute

#
any(role in nflRoleListNames for role in ctx.user.roles)

this is basically the same as a for loop and can be re-written like so:

for role in ctx.author.roles:
    if role not in nflRoleListNames:
        return False
return True

perhaps that will make it a bit easier to comprehend

slate swan
#

I see

#

yea so how do I get the name?

fading marlin
#

since you're iterating over a list of Roles, each item will yield a Role object. Roles have a name attribute which you can use to get the name of the role

slate swan
fading marlin
#

almost

for role in ctx.author.roles:
    if role.name not in nflRoleListNames:
        return False
return True

how would you translate that to the other method? (any(...))

slate swan
#

what

fading marlin
#

I just told you that any(role in nflRoleListNames for role in ctx.user.roles) is pretty much a 1-line for loop and I showed you how to represent it, right?

bright wedge
#

why you dont use role ids?

slate swan
#

32 roles

slate swan
#

yea what about it

fading marlin
slate swan
#
for role in ctx.author.roles:
    if role.name in nflRoleListNames:
        return True
return False
#

this?

fading marlin
#

yeah, you just gotta pass that to the other any(...) way

slate swan
#
      if any(role in nflRoleListNames for role in ctx.user.roles): 
        for role in ctx.author.roles:
          if role.name in nflRoleListNames:
            await ctx.response.send_message('found')
      else:
          await ctx.response.send_message("not found")
fading marlin
slate swan
#

yea

#

I see

fading marlin
#

Roles have a name attribute which returns the role's name...

slate swan
#

yea

fading marlin
#

sooooo

slate swan
fading marlin
#

remove the if

slate swan
fading marlin
#

there ya go

#

so you replace that with role in nflRoleListNames

slate swan
#

if any(role.name in nflRoleListNames for role in ctx.user.roles):

fading marlin
#

there ya go :D

slate swan
#

replace both role or just first one?

fading marlin
#

the second one, but yeah, not both

slate swan
#

alr thanks ill test

#
  if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
      if any(role in nflRoleListNames for role.name in ctx.user.roles): 
            await ctx.response.send_message('found')
      else:
          await ctx.response.send_message("not found")
  else:
    await ctx.channel.send("You are not a coach.", hidden=True)
#
Traceback (most recent call last):
  File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 26, in sign
    if any(role in nflRoleListNames for role.name in ctx.user.roles):
  File "main.py", line 26, in <genexpr>
    if any(role in nflRoleListNames for role.name in ctx.user.roles):
NameError: name 'role' is not defined

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

Traceback (most recent call last):
  File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'sign' raised an exception: NameError: name 'role' is not defined
fading marlin
#

oh, no, yeah, you add role.name to the first role. Sorry, I thought you were referring to the if statements

slate swan
#

ok thanks ill try again lol

#
      if any(role.name in nflRoleListNames for role in ctx.user.roles): 
            await user.add_roles(role.name)
#

what about adding a role?

fading marlin
#

which roles do you want to add?

slate swan
#

the ones it found in my roles that are in the list

fading marlin
#

let's say you have the Arizona Cardinals role, what should the bot do?

somber sky
#

add arizona cardinals to the guy you signed

slate swan
#

add that role to the user I select if they dont have a role thats in the list

fading marlin
#

oh, alright, well you could use utils.find to get the role and add it

slate swan
#

how would I get the name tho

somber sky
fading marlin
#

looks like you guys aren't using the same library

slate swan
#

ctx.author.roles

fading marlin
slate swan
#

why are you even using role names when IDs are easier to use and compare

somber sky
#

@fading marlin how come when the user doesn't have FO, GM, HC role it doesnt do anything but when it only has a coach role it says you are not a coach

@slash.slash(description='Sign a player.')
async def sign(ctx, user: discord.Member):
  FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
  GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
  HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
  teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.author.roles)
  if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
      if any(role.name in nflRoleListNames for role in ctx.author.roles): 
            await user.add_roles(teams) 
      else:
          await ctx.send("You are not a coach.", hidden=True)
          print("User was not a coach.")```
#

when ur not a coach it doesnt say anything

#

it shoiuld say u are nopt a coach

#

ooops wrong command

shrewd fjord
#

Make a list

#

No

#

Nvm u r doing to hardly tho

#

if FORole or HcRole in ctx.author.roles:
...

slate swan
#

Hey i've never coded a discord bot and im just trying to see if im good at it or not. Anyone able to give me any pointers on how to start or the basics?

slate swan
#

yes.

#

you'll start with choosing a library for bot development discord.py ( or its forks) and hikari are some of the popular ones

#

This is a Test to know if you are ready to make a bot using discord.py:

A: in your words, what is the purpose of a For Loop?
B: what is Blocking? and why do you have to use Async for a discord bot?
C: how do you know if a line of code is inside a Block or Scope (like a Function, Class, For Loop, etc...); 
and how do you make that piece of code be outside of the Block or Scope?
D: if you have to make an HTTP Request with your bot, what Libriary would you use?
E: in your words, what is Object Oriented Programming (OOP) and how does it get used in python?
F: what are Fstrings (3.6+) and how can you use them to just get 2 Decimal Places of a Long Float?
G: what is Try-Except, and how can you use it to except Specific Errors?
H: how would you Force to get an Error in the case of not getting one (or atleast know where the problematic line is)?
I: what are the use case of Function Decorators? and what are they really in the background?
J: how would you store Multiple Pieces of Data that are related to more data? (Example: Name1 = James, Name2 = Steve, etc...)

here's some basic things you need to know about

#

you don't need to answer them here lol, but just have a look and you can evaluate yourself

#

ok

somber sky
#

How would I make it where if they are on a different team it will not go through? @fading marlin

@slash.slash(description='Sign a player.')
async def sign(ctx, user: discord.Member):
  FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
  GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
  HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
  channel = bot.get_channel(Transactions)
  teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.author.roles)
  signembed = discord.Embed(title='Franchise Signing', description =f'{teams.mention} have **signed** {user.mention}`{user}`\n\n > **Coach:** {ctx.author.mention}`{ctx.author}`\n> **Roster:** 0/24',timestamp = datetime.datetime.utcnow())
  signembed.set_footer(icon_url = ctx.author.avatar_url, text='{}'.format(ctx.author))
  signembed.set_author(name=f"{ctx.guild.name} Transactions", icon_url=f"{ctx.guild.icon_url}")
  if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
      if teams in user.roles:
       await ctx.send(f'User is already on the {teams.mention}', hidden=True)
       await ctx.channel.delete(embed=signembed)
      if any(role.name in nflRoleListNames for role in ctx.author.roles): 
            await user.add_roles(teams) 
            await ctx.send(f"Signed {user.mention}", hidden=True)
            await channel.send(embed=signembed)
      else:
          await ctx.send("You are not a coach.", hidden=True)
          print("User was not a coach.")```
polar dawn
#

Hi. I want my Discord bot to have a slash command as well as normal command that can be executed with the bot prefix. But I don't want to use hybrid commands as rewriting will take a lot of time tho.

So my question is,
How do I make a slash command with

bot = commands.Bot(command_prefix=get_prefix, intents=intents, case_insensitive=True, help_command=None)

(im sorry if it's very complicated to understand.)

grand hazel
#

how do i use ctx.guild.members is im using slash command?

@tree.command(name = 'stuff', description = 'do stuff')
async def stuff(interaction: discord.Interaction)
    for members in
slate swan
#

!d discord.Interaction.guild

unkempt canyonBOT
grand hazel
slate swan
slate swan
#
@bot.command()
async def testform(ctx):
    form = Form(ctx,'Title')
    form.add_question('Question 1','first')
    form.add_question('Question 2','second')
    form.add_question('Question 3','third')
    result = await form.start()
    return result

Anyone know of something similar for discord.Interaction/app_commands

fast musk
#

wtf is Form()

#

some nextcord/pycord thing?

slate swan
#

nvm

#

its called modals on interaction

#

thats why i couldnt find it

fast musk
#

ah yes

#

who uses Form though? That seems rather opinionated for something Discord might expand on later

#

I guess right now it kind of works... until they add support for another component 😄

fallow tree
#

i'm trying to make a bot when the user uses !image <cat> or whatever it just google it and use the first image and save the url to my sheety spreadsheet, the issue is its detecting the onmessage event and after that its coming to client.run(), its not going through the remaining lines of code.please help me ❤️

naive briar
#

What's the problem

#

Also use a async http client instead of requests

#

Also wait

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

sullen roost
#

am trying to put a streaming activity on my bot but its showing
AttributeError: 'Command' object has no attribute 'Streaming'
here is the code:

await client.change_presence(activity=discord.Streaming(name="streaming", url="https://www.twitch.tv/#"))
slate swan
#

don't make a command function called discord

slate swan
#
discord.ui.TextInput

Does anyone know how to convert the result of a modal to an integer? I am trying to subtract the result by a number but it gives this error

- TypeError: int() argument must be a string, a bytes-like object or a real number, not 'TextInput'

I tried to add int but the result still does not convert

rank = self.rank
rank = rank - 100
print(rank)

I tried to add a style attribute so the result is already an integer but it seems like the only three options are short, paragraph, and long

shrewd fjord
#

Ez as that

naive briar
#

!d discord.ui.TextInput.value

unkempt canyonBOT
shrewd fjord
#

🆒

slate swan
shrewd fjord
#

....

#

Same error?

shrewd fjord
#

Just try 💀

naive briar
#

Or just get the value from it then convert

shrewd fjord
slate swan
#

when i added the str in the first part it worked thank you

winged linden
#

how can I check if someone's discord account is over 14 days old

severe mural
shrewd fjord
winged linden
severe mural
#

and other error last final:

#
async def whois(ctx, *, user: discord.Member = None):```
winged linden
#

thanks

shrewd fjord
#

member.created_at

shrewd fjord
shrewd fjord
severe mural
shrewd fjord
#

slash command's name can't be uppercase

naive briar
#

Read the error

#

That's your answer

shrewd fjord
#

yep

severe mural
shrewd fjord
severe mural
#

only example "m", not "M"?

shrewd fjord
#

yep

severe mural
#

hmm ok check.

shrewd fjord
#

on docs u will find the conditions

severe mural
#

yeah but why no "M"

shrewd fjord
#

like ig 32 is max character

naive briar
#

Ask Discord why they don't allow it

shrewd fjord
#

i forgot

shrewd fjord
severe mural
#

i see.

#

oh other error said: @client.tree.command(name="buypremium", description='Buy Premium SuperKenos') async def premium(ctx, self):".

#

TypeError: parameter 'self' is missing a type annotation in callback 'premium'

shrewd fjord
#

it's not cog neither a class

severe mural
#

ah think

#

done solution.

shrewd fjord
severe mural
#

okay testing.

shrewd fjord
#

@naive briar which db is best to learn? hm ?

#

Filter=Easy

naive briar
#

I'm not a database expert 🐈

shrewd fjord
naive briar
#

But probably SQLite databases or mongodb

shrewd fjord
#

Cool, Thanks for ur suggestion ;]

winged linden
#
age = datetime.utcnow() - user.created_at
#

TypeError: can't subtract offset-naive and offset-aware datetimes

severe mural
#

@shrewd fjord i see problem there error red "discord.app_commands.errors.CommandNotFound: Application command 'show-manager-channel-testing' not found"

#

await interaction.response.send_message(embed=embed)

winged linden
#

but if I do datetime.datetime.utcnow() I get an error aswell

severe mural
naive briar
unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
severe mural
#

ctx change think "interaction: discord.Interaction"

severe mural
shrewd fjord
#

also it's positional parameter so np

severe mural
#

yeah is slash commands

shrewd fjord
severe mural
winged linden
shrewd fjord
#

not this stuff

severe mural
#

sigh ok code:

shrewd fjord
severe mural
shrewd fjord
#

slash command's is totally diff from normal commands

naive briar
#

That's probably for prefix commads

severe mural
#

hmmm

shrewd fjord
cedar fiber
#

anyone know the fastest way to scrape someones newest tweet?

shrewd fjord
#

if still getting same error xd

naive briar
#

!d discord.app_commands.checks.has_role

severe mural
#

.. sigh ok

unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
severe mural
#

moment

severe mural
# shrewd fjord show the code beneath of it now
@commands.has_role("Channels Manager")
async def show_manager_channel(ctx):

    embed = discord.Embed(
        title="⚙️ CHANNELS MANAGER | SUPERKENOS ⚙️", colour=0xAC00FF)
    cur.execute("SELECT * FROM x WHERE x =%s",
                (ctx.guild.id,))

    configured_channels = cur.fetchone()

    #print(configured_channels)

    if configured_channels == None:
        await interaction.response.send_message("A first show manager channel must be configured **/update-manager-channel** ⚠")
        return

    #print(f"Suggest ID = {suggest_channel[1]}")
    embed.add_field(name="💡 Suggest",  value=f"<#{configured_channels[1]}>")

    #print(f"Giveaway ID = {suggest_channel[2]}")
    embed.add_field(name="🏆 Giveaway",  value=f"<#{configured_channels[2]}>")

    embed.add_field(name="🥇 Role Giveaway",
                    value=f"<@&{configured_channels[3]}>")

    # change update
    embed.set_footer(
        text="📝 Change to channels this command /update-manager-channel")
    embed.set_footer(
        text="🚨 Don't forget to create role ´ Channels Manager - Giveaways Manager´ has been can permission command")

    await interaction.response.send_message(embed=embed)```
severe mural
#

but my little understand hard

#

i am no good english and little english

#

my spanish.

#

and no experience "docs"

shrewd fjord
#

broooooooooooooo

#

it will
ctx.reponse.send_message() ;-;

severe mural
#

ahh

#

hmm ok try.

flat pier
#

also, just dont name things like interaction ctx

#

it just causes confusion and is on top of that, pointless

severe mural
shrewd fjord
#

and
from discord import app_commands
@tree.command()
@app_commands.checks.has_role()

flat pier
severe mural
#

Ok but first spokky.

shrewd fjord
#

again telling whatever u give parameter at first of slash command function

severe mural
shrewd fjord
#

it directly converts to discord.Interaction

severe mural
shrewd fjord
#

u have this 2 options

shrewd fjord
severe mural
severe mural
severe mural
#

maybe?

shrewd fjord
# severe mural yes.
@client.tree.command(name="show-manager-channel", description='Show a manager channel testing')
@discord.app_commands.checks.has_role("Channels Manager")
async def show_manager_channel(interaction):

    embed = discord.Embed(
        title=":gear: CHANNELS MANAGER | SUPERKENOS :gear:", colour=0xAC00FF)
    cur.execute("SELECT * FROM x WHERE x =%s",
                (interaction.guild.id,))

    configured_channels = cur.fetchone()

    #print(configured_channels)

    if configured_channels == None:
        await interaction.response.send_message("A first show manager channel must be configured **/update-manager-channel** :warning:")
        return

    #print(f"Suggest ID = {suggest_channel[1]}")
    embed.add_field(name=":bulb: Suggest",  value=f"<#{configured_channels[1]}>")

    #print(f"Giveaway ID = {suggest_channel[2]}")
    embed.add_field(name=":trophy: Giveaway",  value=f"<#{configured_channels[2]}>")

    embed.add_field(name=":first_place: Role Giveaway",
                    value=f"<@&{configured_channels[3]}>")

    # change update
    embed.set_footer(
        text=":pencil: Change to channels this command /update-manager-channel")
    embed.set_footer(
        text=":rotating_light: Don't forget to create role ´ Channels Manager - Giveaways Manager´ has been can permission command")

    await interaction.response.send_message(embed=embed)```
shrewd fjord
#

;-;

severe mural
#

AttributeError: module 'discord.app_commands' has no attribute 'has_role'

#

hmm

naive briar
severe mural
#

discord.app_commands.errors.CommandNotFound: Application command 'show-manager-channel-testing' not found

#

error same sigh no solution?

flat pier
#

do you have any logs saying you're ratelimited when you restart your bot @severe mural

shrewd fjord
#

like oudated

severe mural
shrewd fjord
severe mural
#

:/

severe mural
#

kick and again back bot?

severe mural
shrewd fjord
severe mural
shrewd fjord
#

restarting on code

severe mural
#

Yeah already.

#

error same :/

#

no idea much problem solution.

shrewd fjord
#

make sure your appcommands scope enabled on dev portal while inviting

shrewd fjord
severe mural
#

name="show-manager-channel", description='Show a manager channel testing') think?

shrewd fjord
#

but this shouldn't be the problem tho

severe mural
#

hmmm

shrewd fjord
#

just try ig

severe mural
shrewd fjord
#

name="show" do this 😂

#

and try

#

also make sure u have required role

severe mural
#

Okay try.

shrewd fjord
#

also make sure u didnt made any typo mistake on has_role

severe mural
#

@shrewd fjord i see

#

think no found show-manager-channel-testing but addd there

#

is okay solution. Maybe yes restart bot kick and back bot

#

change name

#

think.

#

but maybe cache discord

#

moment try investigate

#

thanks help @shrewd fjord @flat pier @naive briar

shrewd fjord
#

nice

severe mural
#

next soon help you 🙂

#

happy.!