#discord-bots

1 messages · Page 220 of 1

slate swan
#

Perhaps due to the bot being restarted?

#

If that's the case then you can register the view as a persistent view.

#

!d discord.ext.commands.Bot.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
slate swan
#

Try this out, though I'm not sure what else could be causing your view to fail other than the bot restarting or an unhandled exception

scarlet aurora
#

@sick birch u available now?

fading marlin
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
blissful badge
#

got it!

scarlet aurora
#

can someone help

#

@ashen notch

gusty flax
scarlet aurora
#

alr so I run this code locally and it works ```py
@commands.group()
async def help(self, ctx):
if ctx.invoked_subcommand is None:
embed = discord.Embed(
colour=0x2F3136
)
embed.add_field(name="Main", value=">help (shows this command)\n>crypto\n>music help\n>changelog", inline=False)
embed.add_field(name="Fun", value=">fun help\n>quote\n>cmds", inline=False)
embed.add_field(name="Admin", value=">admin help\n>media help", inline=False)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/949733110050857051/964831939989209138/tmgmidvitelogonowords.png")
await ctx.send(embed=embed)

#

but as soon as I put it on my hoster, all commands in this group just isn't found when called

#

I use something.host and I made sure the environment has everything pip installed correctly

#

here is an example of a command in this group py @help.command() async def admin(self, ctx): embed = discord.Embed( title=f"Admin Commands", description=f">ban\n>unban\n>mute\n>tempmute\n>unmute\n>banlist", colour=0x2F3136 ) embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/949733110050857051/964831939989209138/tmgmidvitelogonowords.png") await ctx.send(embed=embed)

ashen notch
#

Why me specifically?

scarlet aurora
#

cuz ik ur smart

ashen notch
#

Debatable

scarlet aurora
#

u spend 24 hours a day on discord

#

do u not remember me mr hemlock

gusty flax
#

lol

ashen notch
#

I do remember, yeah.

scarlet aurora
#

ye, man has active developer now, man is on another level to you peasants without it

#

@gusty flax u know why that aint working?

gusty flax
ashen notch
#

You've made sure to restart the bot?

#

Positive the code is there, etc.

scarlet aurora
#

yes

#

nvm

#

the cogs folder is fucking empty

ashen notch
#

That would do it

scarlet aurora
#

alr ty

#

fixed

#

bro something host is so slow 💀

#

@ashen notch

#

while ur here

#

do u recommend me duplicating each prefix command to have a slash command version?

#

@ashen notch?

fading marlin
#

hybrid commands exist 🤷

scarlet aurora
#

can u show me an example of one

fading marlin
#

!d discord.ext.commands.hybrid_command

unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").

The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.

Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

New in version 2.0.
fading marlin
#

so basically just replace your normal prefix command

@commands.command()
async def mycommand(self, ctx: commands.Context, ...):
    ...

with a hybrid decorator

@commands.hybrid_command()
async def mycommand(self, ctx: commands.Context, ...):
    if ctx.interaction is not None:
        # command is being called as a slash command
    else:
        # command is being called as a prefix command
scarlet aurora
#

why do u need that if ctx.interaction

#

it's not like I care which way they call it

scarlet aurora
# fading marlin so basically just replace your normal prefix command ```py @commands.command() a...

is this good? py @discord.ext.commands.hybrid_command(name="membercount", description="Shows members", with_app_command=True) @commands.command() async def membercount(self, ctx): embed = discord.Embed( title="Member Count", description=f"There are currently ``{ctx.guild.member_count}`` member(s) in ``{ctx.guild.name}``", colour=0x2F3136 ) embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/949733110050857051/964831939989209138/tmgmidvitelogonowords.png") await ctx.send(embed=embed)

fading marlin
fading marlin
scarlet aurora
#

ok

slate swan
#

!d await Client.wait_for

unkempt canyonBOT
smoky sinew
#

how many times do u need to be reminded

slate swan
dense flower
#

hey guys, does anyone have a favourite vps to host their bots? tried searching in the searchbar but didn't seem to be any concrete answers. Looking for something relatively easy to use and wanted some feedback from people who i know'll give it straight rather than a sponsored yt vid lmao <33

smoky sinew
dense flower
smoky sinew
#

one server with 100 users per bot you mean?

dense flower
#

i meant like i'm gonna be running 5 bots on 5 different discord servers, and there's about 100 potential users that will interact with that bot

#

hopefully that clarifies it a bit, if not lmk lemon_sweat

#

discord servers i should add*

smoky sinew
#

i think their plans are pretty cheap, you shouldn't have any problems but keep in mind the rate limiting since you will be on the same ip

dense flower
#

ah ok, is there a way to get around the rate-limiting? or is it just buy another machine haha

#

oh looking into it it doesn't seem like it'll make enough requests to worry about that for now haha

dense jackal
#

How to install discord components

sick birch
dense jackal
#

Yes

dense jackal
sick birch
dense jackal
# sick birch It's already there for you, in discord.py

import discord
import datetime
from discord.ext import commands
from discord_components import Button, Select, SelectOption, ComponentsBot, interaction
from discord_components.component import ButtonStyle

this does not work

sick birch
#

You don't need discord_components

#

That's a third party library and IIRC deprecated a while ago? (might be confusing it with another package, but still)

dense jackal
#

So I could just delete it?

sick birch
#

Yes

old oracle
#

Hey guys, I purchased a bot from someone and they just handed me a bunch of files and won’t help me. If someone could help me it would be greatly appreciated!

#

Can pay dm me@

hasty rain
#

''' py

#

`py
import discord
from discord.ext import commands

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

.hello

@client.event

async def on_ready():
print( 'Bot connected' )

@client.commands( pass_context = True )
async def hello( ctx ):
await ctx.send('Hello. I am a Bot for discord')

Connect

token = open( 'Token.txt', 'r' ).readline()

client.run( token )`

#

does not work

#

why i have no idea

#

😭

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.

hasty rain
#

I did not get anything

vocal snow
#

are you new to python?

hasty rain
#

Почти

vocal snow
#

I do not speak that language, sorry

hasty rain
#

I understand a little

vocal snow
#

Discord.py is a complex library and you'll need to know python basics before you can use it

#

!resources

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.

vocal snow
#

you can find some free courses and books here

hasty rain
#

Спасибо

hasty rain
#

` py

#
import disnake
from disnake import CommandInteraction
from disnake.ext.commands import Bot

bot = Bot()

@bot.slash_command(
    name="hello",
    description="A simple hello command."
    guild_ids=[...],
)
async def hello(inter: CommandInteraction) -> None:
    await intel.send("hello!")

bot.run("2fb5f8a5e1758631227912159fde4c0da7218bfbf67c38b6c3750cbe434fb2e1") ```
#

did everything according to the instructions

#

not working again

#

😑

meager chasm
#

guild_ids=[100000, 200000] etc

#

And reset your token

#

Don't share it with anyone

hasty rain
#

but i'm just tired

#

I want to make my own unique bot for my gaming clan

#

and I can't

#

I just want to see him at least online

scarlet aurora
vale wing
scarlet aurora
#

so sad

vale wing
#

It looks like hash tbh

scarlet aurora
#

well unfortunatly he will be in the dark for a long time mr bond

vale wing
#

Lightskin stare

scarlet aurora
#

@hasty rain send code and errors

#

entire code (remove ur token)

vale wing
#

I believe that's his only code

#

Ppl already explained what to do

scarlet aurora
#

well send it again

#

oh so u fixed it?

vale wing
#
  1. Use InteractionBot instead of Bot
  2. Replace guild_ids=[...] with list of actual ids
  3. If you are trying to run it with the same "token" it is actually not a token
scarlet aurora
#

lol

#

alright

meager chasm
slate swan
hasty rain
#

understood nothing

glad cradle
vale wing
#

Mm idk how to explain easier without going spoonfeed

slate swan
maiden fable
hasty rain
shrewd apex
glad cradle
thin raft
#

!code

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

vale wing
#

Because you are syncing it only with particular server

#

Then sync it globally 😃

#

Here comes my complete absence of knowledge about syncing in dpy

#

Iirc you need to remove copy_global_to line and remove guild kwarg from sync

thin raft
#

async def setup_hook(self):
await self.tree.sync()

rugged shadow
#

how do bots like GiveawayBot not have a presence

#

like not online, offline, or anything, it just shows their pfp

winged coral
#

Show me? 🤔

#

Oh you might mean a webhook

#

They might be sending the messages from a webhook which wouldn't have a presence

slate swan
slate swan
#
import discord
import asyncio

# Токен доступа бота
TOKEN = "токен"

# Инициализация клиента Discord
intents = discord.Intents.all()
client = discord.Client(intents=intents)
prefix_vis = "!"

# Функция, которая отправляет сообщения
async def send_message(channel, message_text, time, count, color=None):
    paragraphs = message_text.split('\n')
    for i in range(count):
        await asyncio.sleep(time)
        if color:
            embed = discord.Embed(title="Отправленное сообщение", color=color)
            for paragraph in paragraphs:
                embed.add_field(name='\u200b', value=paragraph, inline=False)
            await channel.send(embed=embed)
        else:
            message = '\n'.join(paragraphs)
            await channel.send(message)




# Событие подключения бота к Discord
@client.event
async def on_ready():
    print("Logged in as {0.user}".format(client))

# Событие при получении сообщения
@client.event
async def on_message(message):
    global prefix_vis
    
    # Проверяем, что сообщение написал не бот
    if message.author == client.user:
        return

    # Проверяем, что сообщение начинается с префикса бота
    if not message.content.startswith(prefix_vis):
        return

    # Получаем команду и аргументы из сообщения
    command, *args = message.content.split()

    # Проверяем, что команда - "!send"
    if command == prefix_vis + "send" or command == prefix_vis + "sendemb":
        # Проверяем, что переданы все аргументы
        if len(args) < 2:
            embed = discord.Embed(title="Ошибка", description="Недостаточно аргументов. Использование: !send <время_в_секундах> <количество> <сообщение>", color=0x2f3136)
            await message.channel.send(embed=embed)
            return


        # Парсим аргументы
        try:
            time = int(args[0])
            count = int(args[1])
            message_text = ' '.join(args[2:])
        except ValueError:
            embed = discord.Embed(title="Ошибка", description="Неверные аргументы!", color=0x2f3136)
            await message.channel.send(embed=embed)
            return

        # Создаем сообщение, которое нужно отправить
        color = None
        if command == prefix_vis + "sendemb":
            color = 0x2F3136
        send_message_task = asyncio.create_task(send_message(message.channel, message_text, time, count, color))

        # Отправляем сообщение с подтверждением
        if color:
            embed = discord.Embed(title="Отправка сообщений", description=f"Сообщение '{message_text}' будет отправлено {count} раз с интервалом в {time} секунд.", color=color)
        else:
            embed = discord.Embed(title="Отправка сообщений", description=f"Сообщение '{message_text}' будет отправлено {count} раз с интервалом в {time} секунд.", color=0x2F3136)
        await message.channel.send(embed=embed)

    # Проверяем, что команда - "!prefix"
    elif command == prefix_vis + "prefix":
        # Проверяем, что передан аргумент
        if len(args) < 1:
            await message.channel.send("Usage: !prefix <new_prefix>")
            return

        # Изменяем префикс бота
        prefix_vis = args[0]
        await message.channel.send(f"Prefix changed to '{prefix_vis}'")

# Запускаем бота
client.run(TOKEN)

Can you change the code so that the paragraphs in the message argument (!send & !sendemb) are counted in the send_message function?
Example of how it shouldn't be:

#

Example of how it should be:

#

What error does it output?

vocal snow
#

intents = discord.Intents.default()

#

You aren't enabling the default intents btw

slate swan
#

I'll help you now

#
import discord
from discord import app_commands

MY_GUILD = discord.Object(id=12344)

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        # Создаем объект CommandTree и передаем ему клиент Discord
        self.tree = app_commands.CommandTree(self)

    async def on_ready(self):
        # Вызываем метод setup_hook после того, как клиент Discord готов к работе
        await self.setup_hook()
        print(f"{self.user} has connected to Discord!")

    async def setup_hook(self):
        # Используем объект CommandTree для создания глобальной команды
        self.tree.add_command(ping)
        # Копируем глобальную команду в указанную гильдию
        await app_commands.CommandTree(self).copy_global_to(guild=MY_GUILD)
        # Синхронизируем команды в указанной гильдии
        await app_commands.CommandTree(self).sync(guild=MY_GUILD)

# Создаем объект InteractionCommand и указываем название команды
@discord.app_commands.slash_command(name="ping")
async def ping(interaction: discord.Interaction):
    # Отправляем сообщение в текстовый канал, в котором была выполнена команда
    await interaction.response.send_message("Pong!")

intents = discord.Intents.default()
intents.members = True

client = MyClient(intents=intents)
client.run("TOKEN")
#

Corrected code

#

There are several problems in the above code that can lead to errors when executing commands.

copy_global_to and sync are not methods of the Command Tree object, but methods of the app_commands object. In order for these methods to work, you need to create an app_commands.Command Tree object and pass the Discord client to it as an argument.
In the ping method, you return the result of executing the Interaction Response.send_message method, but this method does not return anything. You need to use the Interaction Response.send method and pass the message text or discard object to it.Message as an argument.

vocal snow
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
slate swan
vocal snow
#

Idk copying code from ChatGPT isn't a good idea

slate swan
#

okey

mighty sun
#

hello, i have question please how to put all of them on the same line ? because I have a lot of bot.command() and I don't like it... I would like to gather them all

slate swan
#

If you wanna have 10 commands you need 10 @bot.command()

vale wing
dense flower
#

Hey guys, I just wanted to check that i'm doing this in a normal way and if anyone had any feedback.

So i'm sorting a /setup for my bot and rn it's /setup (pickachannel). I'm currently storing that channel inside of a database and then whenever i need to send a log, pulling that channel id back from the DB. Is that the correct way of doing things?

sick birch
dense flower
sick birch
#

Or more complex with a redis caching layer

dense flower
# sick birch Can be as simple as a dict

oh yeah I get how to cache it in that respect, but what I mean is i'm unsure how to cache it per-server. Rn I think i'm just a bit confused as to how the bot can keep data internally without other servers accidentally interacting with the wrong data

#

like if server1 does /setup channel and caches the data, how does server2 not also cache that data, as it's the same bot rather than referencing via a db

vocal snow
#

guild_id: channel_id dict?

#

as long as you have the guild id, you can uniquely id the data for each server

dense flower
#

yeah I guess i'm just overcomplicating it in my head. i'll go play around with it and hopefully i'll get it haha

#

thanks though <33

karmic nimbus
#

how do i get user object from user display name?

vale wing
karmic nimbus
#

arg

vale wing
#

Typehint it with discord.User, just like this

async def cmd(ctx, user: discord.User)```
However I am not sure if it supports name-only conversion
karmic nimbus
#

without mentioning them

vale wing
#

!d discord.ext.commands.UserConverter

unkempt canyonBOT
#

class discord.ext.commands.UserConverter(*args, **kwargs)```
Converts to a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

All lookups are via the global user cache.

The lookup strategy is as follows (in order)...
vale wing
#

Yeah 4th strategy is lookup by name, so will work

karmic nimbus
#

tyty

rocky trench
vale wing
#

I never said it doesn't

rocky trench
#

Display name or just name wont work tho

vale wing
rocky trench
#

By name works?

vale wing
#

As you can see

rocky trench
#

That doesn't make any sense, there can be multiple people with the same name no?

vale wing
#

At least it is documented

vale wing
#

It probably selects the first matching

rocky trench
vale wing
#

Agreed

unkempt canyonBOT
#

discord/ext/commands/converter.py lines 319 to 320

predicate = lambda u: u.name == arg
result = discord.utils.find(predicate, state._users.values())```
scarlet aurora
#

@sick birch

#

or @vale wing

#
    @discord.ext.commands.hybrid_command(name="giveaway", description="Sets up a giveaway")
    async def giveaway(self, ctx,  winners, time: TimeConverter = None, prize):
        embed = discord.Embed(
            title="Giveaway",
            description=f"There will be only be {winners} winner(s)",
            colour=0x2F3136
        )
        embed.add_field(name=f"This giveaway is for a prize of {prize}", value=f"Giveaway will last for {time}")
        await asyncio.sleep(time)

        await ctx.send(embed=embed)```How do I make it so that all the arguments are not optional
vale wing
#

What

vale wing
scarlet aurora
#

ok so remove = None

#

ty

formal basin
mental quail
#

why do i get a invalid stynax thing

velvet compass
mental quail
velvet compass
#

Are you currently in the python REPL instead of a command prompt?

mental quail
#

im using VSC

#

i saved the file from python

sick birch
formal basin
#

What does this error mean

sick birch
sick birch
#

Particularly interaction and role

formal basin
#

Yes.

#

I see that

sick birch
#

That's what a typehint is

#

Discordpy is telling you that you're missing a typehint for that parameter

formal basin
#

I don’t know what to put

hallow kernel
#

Ah

sick birch
hallow kernel
#

who is that semaphore?

formal basin
hallow kernel
#

i see something like "weak network" but...

#

its not weak

formal basin
#

I have never seen this error before

sick birch
#

There's no emoji type

#

I think you just need users to enter in the emoji ID and parse it yourself

formal basin
sick birch
#

Yes

formal basin
sick birch
#

You could probably build a custom transformer

#

I haven't used those yet but there are examples in the GitHub repository

naive umbra
#

Anyone familiar with this error from discord.py:```
ModuleNotFoundError: path attribute not found on 'src.events.member' while trying to find 'src.events.member.py'

trying to integrate cogs to my bot, here is how my hook function currently looks like:```py
async def setup_hook(self):
    for cog_type in ["events", "commands"]:
        for module in os.listdir(f"{constants.SRC_PATH}/{cog_type}"):
            await self.load_extension(f"src.{cog_type}.{module}")

my directory structure is as follows:```
project-root/
.git/
.vscode/
src/
commands/...
events/...
main.py
bot.py
README.md
LICENSE

for more context, this is how my `src/events/member.py` looks like:```py
from discord.ext import commands
from ..bot import Bot


class MemberEventsCog(commands.Cog):
    pass


async def setup(bot: Bot):
    await bot.add_cog(MemberEventsCog)
shrewd apex
#

if the running directory is src and running main.py path to cog will be events.member

#

and not src.events

naive umbra
#

tried events.member as well, then it's unable to find the module altogether

shrewd apex
#
async def setup(bot: Bot):
    await bot.add_cog(MemberEventsCog)
async def setup(bot: Bot):
    await bot.add_cog(MemberEventsCog(bot))
naive umbra
#

yeah i solved both the problems, one of them is the one you sent, i forgot to instantiate the cog in the setup functions

#

but i also forgot to strip the .py extension when loading the module in the setup hook

shrewd apex
#

aight cool

naive umbra
#

smh when am i gonna stop dealing with these silly bugs in this programming career

dense flower
#

Hey guys, i'm trying to use SQL to manage my database but i'm struggling to wrap my head around it, is someone able to help me out rq?

I've got the current structure: uID, guildID, address, key but I want a way of flagging the admin account so my bot knows whether or not the /setup command needs to be ran. Would I just make an additional field called admin and set it to True/False?

If anyone has any other suggestions please lmk <33

dull moon
formal basin
#

Anyone know how to fix this

slate swan
#

you cant annotate argument as discord.Emoji

formal basin
karmic nimbus
#

what's wrong? in back commands

@client.command()
async def afk(ctx, reasons: str):
    global afkdict, afkrole, afkuser, member, guild, afkget
    guild = client.get_guild(guild_id)
    afkdict = {}
    afkrole = discord.utils.get(guild.roles, name='AFK')
    afkuser = ctx.author.id
    afkget = guild.get_member(afkuser)
    member = discord.member
    if len(reasons) >= 1:
        afkdict[afkuser] = reasons
        await afkget.add_roles(afkrole)
        await ctx.send(f'your **AFK** is now set to: `{reasons}`')
    else:
        reasons = 'None'
        afkdict[afkuser] = reasons
    

@client.command()
async def back(ctx):
    if afkrole in ctx.author.roles:
        await afkget.remove_roles(afkrole)
        await ctx.send(f'Welcome back! <@{afkuser}>')
        afkdict.pop[afkuser]
    else:
                      await ctx.send(f'You need to AFK first to run this command')
unkempt jungle
#

I have a strange one. I have a discord bot that I have running a loop, but my asyncio.sleep or time.sleep do not work with a variable inside of them. If I put a straight number, its fine.

        await bot.wait_until_ready()
        while True:
                storage = urlGet('https://api.mozambiquehe.re/maprotation?version=2/')
                mapname = storage['battle_royale']['current']['map']
                rankedmap = storage['ranked']['current']['map']
                ltmmapname = storage['ltm']['current']['map']
                ltmmode = storage['ltm']['current']['eventName']
                ## It may look weird that I don't bother with ranked sec remaining, but since it tends to be so long, it doesn't seem worth comparing.
                pubsVC = bot.get_channel(XXXX)
                ltmVC = bot.get_channel(XXXX)
                rankedVC1 = bot.get_channel(XXXX)
                rankedVC2 = bot.get_channel(XXX)
                await pubsVC.edit(name="Pubs : " + mapname)
                await ltmVC.edit(name=ltmmode + " " + ltmmapname)
                await rankedVC1.edit(name="P+ : " + rankedmap)
                await rankedVC2.edit(name="G- : " + rankedmap)
                secondsRemaining = min((storage['battle_royale']['current']['remainingSecs']),(storage['ltm']['current']['remainingSecs']))
                print("Sleeping for " + str(secondsRemaining))
                print(datetime.now())
                await asyncio.sleep(float(secondsRemaining))```
formal basin
#

!d discord.Emoji

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
formal basin
#

Guys which annotation is supported?

sick birch
#

And either use a transformer or parse it yourself

vale wing
#

I believe they are called "converters" tho

formal basin
formal basin
#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
slate swan
#
prefix = input("Enter The Prefix For The Bot |")
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
warnings = {}

@bot.event
async def on_ready():
  print("Setting Status")
  time.sleep(2)
  activity = discord.Activity(type=discord.ActivityType.watching, name=f"Prefix = {prefix} |invite)
  await bot.change_presence(status=discord.Status.online, activity=activity)
  print("Bot is Ready!")```

ment to set prefix but doenst
steep wedge
#

and i realise i have nothing after the with block but even if i add something there it's still

#

the same error

slate swan
#

Also dont use time.sleep in discord bot

#

!d asyncio.sleep use this instead

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
slate swan
#

its ment to set the prefix to what gets chosen at the start

#

but doesnt and just sets the prefix to !

#

Show full code

unkempt jungle
# slate swan !d asyncio.sleep use this instead

I actually found out a little later on the error was occurring before the sleep. I was using a min() function, but piping in strings absentmindedly, which led to junk for the sleep command itself. I am back to using asyncio sleep. I moved away from it for testing.

slate swan
#

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "astro.py", line 268, in serverinfo
em.add_field(name="Region", value=str(guild.region.name).capitalize(), inline=False)
AttributeError: 'Guild' object has no attribute 'region'

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

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'region'

#

i trying to make a serverinfo command

#

my code

cedar scaffold
#

there is no region in Guild @slate swan

slate swan
#

dont know what that means

cedar scaffold
#

remove the line that has region

#

guild object does not have a region attribute you can use, doubt it exists at all

slate swan
#

it does

#

!d discord.Guild.preferred_locale

unkempt canyonBOT
#

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Changed in version 2.0: This field is now an enum instead of a str.

smoky sinew
#

lowercase @discord.ui.button

#

also don't use asterisk import that's how you get conflicts

#

for example

from discord.ui import *
from discord import *

# error, there is both discord.ui.Button
# and discord.Button attributes

how will python know which one to use?

#

yeah, you're going to get an error eventually 🫠

#

you shouldn't really use asterisk imports at all

#

you never know what you are going to import

smoky sinew
#

you can just import it normally instead

#

why

#

sure

#

what's your code

#

what's your code right now

#

you didn't lowercase button though

#
class Menu(discord.ui.View):
    @discord.ui.button(label="my_menu", style= discord.ButtonStyle.green)
    async def my_menu(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        await interaction.response.send_message("hello you clicked me")
slate swan
#

whats wrong with my code this is it

#

# Create a client object
client = discord.Client()

# Define a function to handle messages
@client.event
async def on_message(message):
    # Check if the message was sent by the bot
    if message.author == client.user:
        return
    
    # Check if the message starts with the word "hello"
    if message.content.startswith('hello'):
        # Respond with "Hello, {username}!"
        await message.channel.send(f'Hello, {message.author.name}!')

# Run the bot
client.run('TOKEN')
#

/help

#
TypeError: Invalid class <class 'discord.message.Attachment'> used as an input type for an Option

Using a hosting service to host this website but keep getting this error

smoky sinew
#

your code is very outdated btw

slate swan
#

Oh i used chatgpt

smoky sinew
#

don't

#

it's also against the rules in this server

slate swan
#

Oh

smoky sinew
#

actually only for helping i guess

slate swan
#

Oh

#

okay

#

Where will I get updated code

smoky sinew
#

just use the discord.py documentation, chatgpt can't know about anything after 2021

slate swan
#

k

smoky sinew
#

maybe not with the new plugins lol

karmic nimbus
#

what is self in cogs used for?

merry cliff
#

it’s a class

unkempt canyonBOT
#
Class instance

When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.

class Foo:
    def bar(self):
        print('bar')

    def spam(self, eggs):
        print(eggs)

foo = Foo()

If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.

Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').

Why is this useful?

Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.

Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.

pulsar loom
#

.

unkempt canyonBOT
#
PATH on Windows

If you have installed Python but forgot to check the Add Python to PATH option during the installation, you may still be able to access your installation with ease.

If you did not uncheck the option to install the py launcher, then you'll instead have a py command which can be used in the same way. If you want to be able to access your Python installation via the python command, then your best option is to re-install Python (remembering to tick the Add Python to PATH checkbox).

You can pass any options to the Python interpreter, e.g. to install the [numpy](https://pypi.org/project/numpy/) module from PyPI you can run py -3 -m pip install numpy or python -m pip install numpy.

You can also access different versions of Python using the version flag of the py command, like so:

C:\Users\Username> py -3.7
... Python 3.7 starts ...
C:\Users\Username> py -3.6
... Python 3.6 starts ...
C:\Users\Username> py -2
... Python 2 (any version installed) starts ...
glossy edge
#

It should already, unless your initial command is blocking.

sick birch
#

Seems to me like you can just spin up a bunch of containers for your bots

glossy edge
#

Whats the code for this command?

#

Are you using requests?

#

Don't use requests, use an async alternative like aiohttp

sick birch
glossy edge
#

Show your code.

glossy edge
#

please use formatting

#

I believe* that openai SDK is synchronous. Which means it's blocking.

#

or interact with their API directly

#

Oops that's the wrong lib

strong vessel
#

how do people get hacked when they join discord servers?

velvet compass
#

They scan QR codes

#

Which is something you should only do if it is the official discord login page

mighty sun
#

Hello, I have a problem with the reaction roles, when I want to create a reaction role and I click on the reaction it does not work... we all tried... please help me

vale wing
# velvet compass They scan QR codes

How exactly can a QR grab person's credentials? I am not a web security expert, but logically discord authorisation QRs shouldn't point to some random URLs and app should check that

velvet compass
#

I'd rather not discuss the details on how this happens in a public channel as well, but the bottom line is don't scan any QR code if you aren't logging in to discord

meager chasm
#

You should consider using UI components for this

#

Like Button/Select Menus

mighty sun
#

@meager chasm ok but I don't know how to do it...

meager chasm
#

Here is an example of a simple counter button

#

In essence, you have an instance of discord.ui.View which contains ui components, which you then pass to the view kwarg of Messageable.send

#

Usually it's recommended you subclass View and add the components using the decorators as shown in the example

#

So make sure you properly understand how classes work before this

smoky sinew
#

each QR code is specific to a session and the hackers generate it and get you to scan it to approve the session login

vale wing
#

So key thing is not only discord can "register" those QRs

smoky sinew
#

what do you mean? discord generates them and the hackers just send it to you

sick birch
#

IIRC QR code skips 2fa entirely for the sake of convenience

#

And, of course, in the world of security, convenience is often a trade off to security

maiden fable
#

Yup

wind radish
mighty sun
#

It’s ok thank you all 😉

vale wing
fading marlin
#

unfortunately

static holly
#

hi how can i get ctx.author activity?

#

i tried with ctx.author.activities[0].name, and it dont work

fading marlin
#

there's author.activity too

#

any errors when you try and fetch through activities though?

static holly
#
@commands.hybrid_command(name="twitch", description="montrer aux membres que vous êtes en live sur Twitch!")
    async def twitch(self, ctx, pseudo):
        
        user= f"{pseudo}".capitalize()
        url = "https://www.twitch.tv/"

        await ctx.send ( ":arrow_right:"  f"""**{user}** est en direct sur twitch et joue à "**{ctx.author.activities[0].name}**!"
        
{url}{pseudo}""")```
#

@fading marlin

fading marlin
#

user doesn't have any activities 🤷

#

do you have the presences intent enabled?

static holly
static holly
static holly
fading marlin
#

I call Discord issue

static holly
dense jackal
#

Any free discord bot hosting servers?

merry cliff
#

those are all very very sus

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

slate swan
#

Is this good code

#
import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        # don't respond to ourselves
        if message.author == self.user:
            return
         if message.content.lower() == 'hello':
        await message.channel.send('Hello!')

intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run('TOKEN')
#

hello

ashen flicker
#

how i do install opus to use discord.opus.load_opus('opus')?

ashen flicker
smoky sinew
#

and your if statement indentation is weird

#

looks like it's one space ahead

smoky sinew
ashen flicker
smoky sinew
#

it should be loaded for you automatically

fading marlin
#

OH MY GOD WE HAVE REACTION PERMS NOW

smoky sinew
#

we have had them for a couple weeks now

fading marlin
#

I haven't been around much lately, I just noticed 😅

smoky sinew
#

anyone know which discord libs currently support voice receive?

#

i know pycord does 🥴

fading marlin
#

there's a pr for that in dpy, but it doesn't seem like it's getting anywhere 😔

smoky sinew
#

it never will

#

i don't think danny has any interest in implementing it

fading marlin
#

rip

golden pewter
#

Anyone able to help with my discord bot Q in help section. No rush but would love some professional insight

vital glacier
#

how do i get an delete all the emotes from a message?

smoky sinew
#

what do you mean delete all emotes from a message

vital glacier
#

reactionrole clear basically

#

Remove all reaction roles from a message

smoky sinew
#

!d discord.Message.clear_reactions

unkempt canyonBOT
#

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

Removes all the reactions from the message.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this.
vital glacier
#

well yeah, but how would i get all the emotes on that message?

smoky sinew
#

!d discord.Message.reactions

unkempt canyonBOT
vital glacier
#

ok cant seem to figure it out

#
    @remove.group(
        name='all',
        description='Remove all reaction roles from a message',
        brief='message',
        usage=
        'Syntax: (message link)\n'
        'Example: https://discord.com/../',
        extras={'perms': 'Manage Roles'}
    )
    @commands.has_permissions(manage_roles=True)
    async def remove_all(self, ctx, message_link: str):
        message = message_link.strip("/").split("/")[-1]
        data = await self.bot.db.fetchval('SELECT message FROM reactionroles WHERE guild = $1', ctx.guild.id)
        if data:
            await message.clear_reactions()
            await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1', message)
            await ctx.send('deleted all the rrs')

this is what i got rn

smoky sinew
vital glacier
#

no idea

#

it gives errors, sec, ill show u inna moment

#
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/void/cogs/Configuration.py", line 269, in remove_all
    await message.clear_reactions()
AttributeError: 'str' object has no attribute 'clear_reactions'

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/jishaku/features/invocation.py", line 168, in jsk_debug
    await alt_ctx.command.invoke(alt_ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1642, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1642, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1636, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'clear_reactions'

@smoky sinew

smoky sinew
#

you should use the Message converter instead

vital glacier
smoky sinew
#

no

#
async def remove_all(self, ctx, message: discord.Message):
    data = ...
    if data:
        await message.clear_reactions()
        ...
vital glacier
#

well im not using message: discord.message

#

cus i can use id's and message links

#

hence why im doing message = message_link.strip("/").split("/")[-1]

#

and hence why message_link = str

smoky sinew
#

The lookup strategy is as follows (in order):

  1. Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)
  2. Lookup by message ID (the message must be in the context channel)
  3. Lookup by message URL
vital glacier
#

oh wait fr?

#

never knew LMFAO

smoky sinew
#

what do you think it did

#

if not message id or message link

vital glacier
#

and now my whole command is broken lol

smoky sinew
#

how so

vital glacier
#

sec might just be my database

#

cus it keeps saying its expecting a str but got an int, and when i make it a string it just errors again

smoky sinew
#

what is your code

vital glacier
#

hence why i was doing it with the split/strip method cus that worked

#
    @reactionrole.group(
        name='add',
        description='Add a reaction role to a message',
        brief='message, emote, role',
        usage=
        'Syntax: (message link) (emote) (role)\n'
        'Example: https://discord.com/../ 🤍 White',
        aliases=['create'],
        extras={'perms':'Manage Roles'}
    )
    @commands.has_permissions(manage_roles=True)
    async def add(self, ctx, message: discord.Message, emote: str, role: discord.Role):
            await self.bot.db.execute('INSERT INTO reactionroles (message, role, emote, guild) VALUES ($1, $2, $3, $4)', message.id, str(role.id), emote, ctx.guild.id)
            message = await ctx.channel.fetch_message(message)
            await message.add_reaction(emote)
            await ctx.success("You now successfully added a reaction role")

    @reactionrole.group(
        invoke_without_command=True,
        name='remove',
        description='Remove a reaction role from a message',
        brief='message, emote',
        usage=
        'Syntax: (message link) (emote)\n'
        'Example: https://discord.com/../ 🤍',
        aliases=['delete', 'del'],
        extras={'perms': 'Manage Roles'}
    )
    @commands.has_permissions(manage_roles=True)
    async def remove(self, ctx, message: discord.Message, emote: str):
            data = await self.bot.db.fetch('SELECT * FROM reactionroles WHERE message = $1 AND emote = $2 AND guild = $3',  message.id, emote, ctx.guild.id)
            if data:
                await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1 AND emote = $2 AND guild = $3', message.id, emote, ctx.guild.id)
                await message.clear_reaction(emote)
                await ctx.success("You now successfully removed a reaction role")

    @remove.group(
        name='all',
        description='Remove all reaction roles from a message',
        brief='message',
        usage=
        'Syntax: (message link)\n'
        'Example: https://discord.com/../',
        extras={'perms': 'Manage Roles'}
    )
    @commands.has_permissions(manage_roles=True)
    async def remove_all(self, ctx, message: discord.Message):
        data = await self.bot.db.fetchval('SELECT message FROM reactionroles WHERE guild = $1', ctx.guild.id)
        if data:
            await message.clear_reactions()
            await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1', message.id)
            await ctx.send('deleted all the rrs')
smoky sinew
#

what is the error message?

vital glacier
#
Traceback (most recent call last):
  File "asyncpg/protocol/protocol.pyx", line 168, in prepare
  File "asyncpg/protocol/codecs/base.pyx", line 206, in asyncpg.protocol.protocol.Codec.encode
  File "asyncpg/protocol/codecs/base.pyx", line 111, in asyncpg.protocol.protocol.Codec.encode_scalar
  File "asyncpg/pgproto/./codecs/text.pyx", line 29, in asyncpg.pgproto.pgproto.text_encode
  File "asyncpg/pgproto/./codecs/text.pyx", line 12, in asyncpg.pgproto.pgproto.as_pg_string_and_size
TypeError: expected str, got int

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/void/cogs/Configuration.py", line 228, in add
    await self.bot.db.execute('INSERT INTO reactionroles (message, role, emote, guild) VALUES ($1, $2, $3, $4)', message.id, str(role.id), emote, ctx.guild.id)
  File "/usr/local/lib/python3.8/dist-packages/asyncpg/pool.py", line 560, in execute
    return await con.execute(query, *args, timeout=timeout)
  File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 319, in execute
    _, status, _ = await self._execute(
  File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 1658, in _execute
    result, _ = await self.__execute(
  File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 1683, in __execute
    return await self._do_execute(
  File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 1730, in _do_execute
    result = await executor(stmt, None)
  File "asyncpg/protocol/protocol.pyx", line 183, in bind_execute
asyncpg.exceptions.DataError: invalid input for query argument $1: 1090814952253698059 (expected str, got int)
#

thats for reactionrole add

maiden fable
#

The attribute is a string type but u r giving int

smoky sinew
#

because your column is a string

vital glacier
#

it isnt

#
CREATE TABLE "reactionroles" (
    "role"    VARCHAR(50),
    "message"    BIGINT,
    "emote"    TEXT,
    "guild"    BIGINT
);

#

just changed it to BIGINT, to prevent that

#

and its sending that error, hence why i was using that other method which made it work properly

#

cus whether if i used a link or an id, it just got the id for me and it worked that way

smoky sinew
#

did you use ALTER and UPDATE to set it to a bigint?

vital glacier
#

i recreated the table

#

just to be sure

#

to make sure i didnt make a mistake

#

hence why im sticking to that cus that was proper with my db

smoky sinew
#

sure

vital glacier
#

so this would work then
message = await ctx.channel.fetch_message(message)
if this is my code:

    @commands.has_permissions(manage_roles=True)
    async def remove_all(self, ctx, message_link: str):
        message = message_link.strip("/").split("/")[-1]
        data = await self.bot.db.fetchval('SELECT message FROM reactionroles WHERE guild = $1', ctx.guild.id)
        if data:
            message = await ctx.channel.fetch_message(message)
            await message.clear_reactions(message)
            await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1', message)
            await ctx.send('deleted all the rrs')
pulsar loom
#

Hey guys can anyone tell me why this code is not working

#

import discord
import openai
import os

openai.api_key = 'Api KEy'

def get_gpt_response(prompt):
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
return response.choices[0].text.strip()

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!gpt'):
prompt = message.content[4:]
response = get_gpt_response(prompt)
await message.channel.send(response)

client.run("Hello")

#

please ping me

vocal snow
pulsar loom
#

..

#

ohh

#

so i should do it all

vocal snow
#

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

vocal snow
#

Or you can do it like that ^

pulsar loom
#

..

#

k thank you

vocal snow
#

Create an instance of Intents with the default() factorymethod and then set intents.message_content to True

hasty rain
#

Guys, how can I make the bot at least online?

thin raft
unkempt canyonBOT
#

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

Creating a Bot account is a pretty straightforward process.

hasty rain
#

Чтобы работать с библиотекой и Discord API в целом, мы должны сначала создать учетную запись Discord Bot. Создание учетной записи бота — довольно простой процесс.

#

so he is

#

i mean code

#

he is always offline

thin raft
#

I am not understanding what do you want to do

hasty rain
#

OK

hasty rain
#

Thanks a lot

#

🤣🤣🤣

#

File "<stdin>", line 1

#

even with a ready-made template does not work

#

either I'm the dumbest or the most unlucky

#

🤣🤣🤣

thin raft
#

you should learn how to code first

hasty rain
#

doesn't work even with the template

#

now it’s clear why nothing works, I want to learn python

vocal snow
hasty rain
#

i have a script

#

but it doesn't start

hasty rain
#

🤣🤣🤣🤣🤣

vocal snow
naive briar
#

lol

hasty rain
#

🤣🤣🤣

#

laptop frozen

vocal snow
#

maybe its a sign

hasty rain
#

funny

desert cosmos
#

do you guys start and stop your program every time you tweak something
if not how do you debug ?

hasty rain
#

А разве можно изменять код когда приложение всключено?

glad cradle
#

or if you're in development you can run the Bot with a debugger

desert cosmos
# thin raft wdym

i mean in debugging sometimes you gotta check how a certain line of code is working

#

its annoying to keep running and destroying code again and again

thin raft
#

I personally just add a print per variable

#

and check when a variable doesn't have a value that I want

desert cosmos
thin raft
#

I personally recommend having a production bot and a testing bot

desert cosmos
#

yeah but still don't you think it would be much easier if it can respond to commands with the realtime code

#

so like we can see the changes as soon as code changes

thin raft
#

1 sec let me check something

#

!d discord

unkempt canyonBOT
#

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

Creating a Bot account is a pretty straightforward process.

desert cosmos
#

sure

thin raft
#

maybe?

#

but coding directly on your main bot means if there's any bug while coding it people can abuse it

desert cosmos
#

yeah actually i have separate production and testing ones

desert cosmos
#

just running a command will work

thin raft
thin raft
#
@commands.command()
async def reload_cog(self, ctx: commands.Context, cog: str):
  if ctx.author.id != yourid: return

  await bot.reload_extension(cog)
desert cosmos
#

frick how can i forget, i have the same thing already in my bots code

thin raft
#

lmao

desert cosmos
thin raft
#

💀

#

how much time have you been coding @desert cosmos ?

desert cosmos
#

actually i have recently started again

thin raft
#

again?

desert cosmos
#

is there something wrong in this ?

thin raft
#

it is completely fine, I wast just confused

smoky sinew
#

is pretty much all you need

thin raft
#

jishaku?

smoky sinew
#

it's a cog available on pypi

#

!pypi jishaku

unkempt canyonBOT
unkempt mauve
#

It's happening for the add balance cmd

smoky sinew
#

why don't you just use GroupCog

unkempt mauve
unkempt mauve
#

alr, thanks

shrewd vapor
#

How to get it ?

smoky sinew
#

!d discord.ui.Modal.on_submit @shrewd vapor

unkempt canyonBOT
#

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

Called when the modal is submitted.
smoky sinew
#

simply override this in your modal

#

then use self.text_input (replace with whatever you named it)

shrewd vapor
smoky sinew
#

no

shrewd vapor
#

Oh

smoky sinew
#

why would you be using such an old version anyway

shrewd vapor
#

Bruh...

shrewd vapor
#

I can't update my code to change the version

smoky sinew
#

see this page

shrewd vapor
#

All my commands are slash commands and I don't understand them in version 2.x.x

#

I started discord.py with 1.7.3 but tried to migrate to 2.0 3 months ago but failed after 1 weeks of trying

shrewd vapor
#

!d help

#

!d tree

#

How to initialise command slash and use ?

hushed galleon
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
shrewd vapor
#

Thx

#

I use currently discord.py 1.7.3 I try update to 2.2.x

hushed galleon
#

^

shrewd vapor
#

I have already looked, but I find it incomprehensible

hushed galleon
#

the basic principle is:

  1. define slash command
  2. add command to tree
  3. synchronize tree to discord some time after your bot logs in ```py
    bot = commands.Bot(...)

@bot.tree.command() # tree.command() does 1 and 2 at the same time
async def my_command(interaction: discord.Interaction):
await interaction.response.send_message("Hello world!")

@bot.event
async def setup_hook():
await bot.tree.sync() # running step 3 on login

bot.run(...)```

shrewd vapor
#

I want the slash commands for a whole file that contains all the code but I don't see how to put it and for the slash commands to be on all the servers of the bot

hushed galleon
#

commands are defined as global by default, and sync() without any arguments will sync all your global commands

shrewd vapor
#

Is good ? py @bot.tree.command(name="help", description="View all commands")

hushed galleon
#

er sure, but a help slash command is unusual to have

shrewd vapor
#

Oh xD

hushed galleon
#

users already see descriptions of your commands, so you'd only need that if you can explain something better than the 100-character limit of each description

shrewd vapor
hushed galleon
#
param: discord.Role
     ^^^^^^^^^^^^^^``` they're asking you to give your parameter a typehint
shrewd vapor
#

And here ?

#

reason is just str for give a reason for open ticket

hushed galleon
#

yeah same thing

shrewd vapor
#

reason : str ?

hushed galleon
#

yes

#

its probably also worth renaming ctx to interaction: discord.Interaction so you dont get it confused with normal commands

shrewd vapor
smoky sinew
smoky sinew
# shrewd vapor

it should be interaction, member: discord.Member, reason: str = None

#

you will have to annotate everything so discord knows the type of the argument

shrewd vapor
#

member is just member#0000

smoky sinew
#

then type hint it as discord.User i guess

#

or string

shrewd vapor
#

Digit number is authorized in string ?

smoky sinew
#

yes, string is any text

shrewd vapor
#

No 😦

smoky sinew
#

it's str, not string

shrewd vapor
smoky sinew
#

it's the same thing

#

it's also not ctx, it's interaction

#

ctx is inaccurate

shrewd vapor
#

Just channel_id I edit ctx after

smoky sinew
#

it depends on what you were using before, given that you are not using a converter it would be str again as that is the default for prefix commands

shrewd vapor
smoky sinew
#

it's interaction.user, for the user who started the interaction

#

again replace all ctx instances with interaction

shrewd vapor
#

I have 235 ctx

#

All replace with interaction ?

#

He have send message

smoky sinew
#

on_message does not have ctx or interaction

#

just message

smoky sinew
slate swan
#

Hey, I got a Python script but i have no idea how to connect it with a discord bot. Any ideas on how to?

smoky sinew
#

check out the docs for discord.Interaction and discord.InteractionResponse

shrewd vapor
#
@bot.event
async def on_message(interaction):
    user = interaction.user
    if interaction.channel.type is discord.ChannelType.private:
        return
    if interaction.channel.name != "verification":
        return
    if user.bot:
        if not interaction.embeds:
            await interaction.delete()
    elif not user.bot:
        if interaction.content != ".verif":
            if (interaction.user.guild_permissions.ban_members):
                return
            message = await interaction.reply("Deleting because it's not .verif")
            await message.delete(delay = 5)
            await interaction.delete()
        if ".verif" in interaction.content:
            guild_id = interaction.guild.id
            role_id = database_verif.get_role_id(guild_id)
            role = discord.Object(id=role_id)
            await interaction.user.add_roles(role)
            embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
            embed.set_footer(text = f"Added for {interaction.guild.name}")
            message = await interaction.reply(embed=embed)
            await message.delete(delay = 2)
            await interaction.delete(delay = 2)
            if database_verif_channel.get_channel(guild_id) is None:
                return
            channel_send = database_verif_channel.get_channel(guild_id)
            embed_verif = discord.Embed(title = "Verification Successful Passed", description = f"Verification Successful Passed for:\n<@{interaction.user.id}> | {interaction.user}")
            embed_verif.set_footer(text = f"By {interaction.guild.name}")
            message = await channel_send.send(embed=embed_verif)```Is my on_message 💀
smoky sinew
#

on_messages do not have interactions though

#

it would be async def on_message(message):

shrewd vapor
#
@bot.event
async def on_message(message):
    user = message.user
    if message.channel.type is discord.ChannelType.private:
        return
    if message.channel.name != "verification":
        return
    if user.bot:
        if not message.embeds:
            await message.delete()
    elif not user.bot:
        if message.content != ".verif":
            if (message.user.guild_permissions.ban_members):
                return
            message = await message.reply("Deleting because it's not .verif")
            await message.delete(delay = 5)
            await message.delete()
        if ".verif" in message.content:
            guild_id = message.guild.id
            role_id = database_verif.get_role_id(guild_id)
            role = discord.Object(id=role_id)
            await message.user.add_roles(role)
            embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
            embed.set_footer(text = f"Added for {message.guild.name}")
            message = await message.reply(embed=embed)
            await message.delete(delay = 2)
            await message.delete(delay = 2)
            if database_verif_channel.get_channel(guild_id) is None:
                return
            channel_send = database_verif_channel.get_channel(guild_id)
            embed_verif = discord.Embed(title = "Verification Successful Passed", description = f"Verification Successful Passed for:\n<@{message.user.id}> | {message.user}")
            embed_verif.set_footer(text = f"By {message.guild.name}")
            message = await channel_send.send(embed=embed_verif)```Is good now ?
smoky sinew
#

interactions only apply to slash commands, right-click commands (e.g. right-click on user or message), button/select interactions, and modals

smoky sinew
slate swan
#

Where cani find project’s working?

shrewd vapor
smoky sinew
slate swan
smoky sinew
slate swan
#

oki

smoky sinew
#

it's better to integrate the script into the discord bot, or use the script as a module that you can import in your bot code

slate swan
shrewd vapor
smoky sinew
#

though there is probably a way to simplify this script by a lot

smoky sinew
# shrewd vapor

!d discord.InteractionResponse @shrewd vapor a bot can have different responses to the command

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").

New in version 2.0.
smoky sinew
#

the one you are probably looking for is InteractionResponse.send_message, you can also send things like modals

smoky sinew
# slate swan How?

for starters, put all the NPCs into a dictionary, that way your main code will only be a few lines long

#

if you use a loop

shrewd vapor
slate swan
smoky sinew
smoky sinew
#

and having less lines is usually better in terms of code readability

#

for example:

shrewd vapor
smoky sinew
#
npc_list = {
    "Kaioken Student": 700,
    "Krillin": 1000,
    ...
}

def view_npc_stats():
    for npc_name, npc_stats in npc_list.items():
        print(f"{npc_name} - {npc_stats}") # Kaioken Student - 700, ...

def get_npc_name_from_stats(stats):
    for npc_name, npc_stats in npc_list.items():
        if npc_stats == stats:
            return npc_name

@slate swan

#

you can then easily import this code, or include it in your main bot file

shrewd vapor
#

Ok is good

#

Thanks for your help

slate swan
shrewd vapor
#

My bot enter in a new generation

smoky sinew
#

it would print all of them out if you looped over npc_list

#

hence why i included "..."

shrewd vapor
#

My log functions no longer work 💀

slate swan
#

npc_list = {
"Kaioken Student": 700,
"Krillin": 1000,
"Kid Gohan": 1400,
}

#

could this work?

smoky sinew
#

sure

slate swan
#

and just continue on adding the NPCs into the list

smoky sinew
#

yup

slate swan
#

that finna take long ahh time 😭

#

Can I just integrate it into my bot as it is rn?

#

ive watched YT vids on how to intergrate a code into a bot, and nun of them worked

shrewd vapor
#

on_message_delete
And
on_message_edit doesn't work

I don't have error just he not send the message

naive briar
#

That sounds like average YouTube tutorials

smoky sinew
#

i just wrote the whole thing, took 3 minutes rd_shrug

slate swan
#

Thats crazy, the normal code took me 10+ min to do it

#

Well more

naive briar
slate swan
#

cuz i had to get the npc names etc

smoky sinew
#

i sent it in your dms to not flood chat

shrewd vapor
#
intents=discord.Intents.all()``` I have this
#

xD

slate swan
#

Appreciate it alot 🙏

shrewd vapor
#
@bot.event
async def on_message_delete(message):
    guild_id = message.guild.id
    if database_log_message.get_channel(guild_id) is None:
        return
    channel_send = database_log_message.get_channel(guild_id)
    if message.author == message.author.bot:
        return
    if message.content == ".verif":
        return
    if message.embeds:
        if message.content is None:
            await channel_send.send(message.embeds)
        return
    embed=discord.Embed(title = f"Message deleted in {message.channel}", description = f"{message.author.name} Message deleted", color=discord.Color.dark_purple())
    embed.add_field(name="Message :",value=message.content, inline=False)
    embed.add_field(name = "Account created :", value = message.author.created_at.strftime('%d %B %Y at %H:%M'))
    await channel_send.send(embed=embed)


@bot.event
async def on_message_edit(message_before, message_after):
    guild_id = message_before.guild.id
    if database_log_message.get_channel(guild_id) is None:
        return
    channel_send = database_log_message.get_channel(guild_id)
    if message_before.embeds:
        if message_before.content is None:
            await channel_send.send(message_before.embeds)
        return
    embed = discord.Embed(title = f"Message edited in {message_before.channel}", description = f"{message_before.author.name} message edited", color = discord.Color.dark_purple())
    embed.add_field(name = "Message Before :", value = message_before.content, inline = False)
    embed.add_field(name = "Message After :", value = message_after.content, inline = False)
    await channel_send.send(embed=embed)```
I have this for the logs
slate swan
#

what does this mean?

vocal snow
#

It means the process finished with no errors

slate swan
#

💀

vocal snow
#

You should send your code when there's something wrong with it

vocal snow
#

How are you running the script?

slate swan
vocal snow
slate swan
#

Now i got hella errors

#

@vocal snow any idea how i can get the file back?

smoky sinew
#

least confusing pycharm error message

slate swan
smoky sinew
smoky sinew
#
npc_list: = {

this is not valid syntax, and it would also never run while your bot is running becauseclient.run won't stop

#

instead you should just import responses

#

and use responses.function_name wherever you need it

slate swan
smoky sinew
#

no

#

put import responses at the top

#

along with import discord

slate swan
smoky sinew
#

i did not send that

vocal snow
#

📸muddy caught spoonfeeding

slate swan
#

Ohhhhh

smoky sinew
#

@slate swan does it work?

slate swan
smoky sinew
#

why not?

slate swan
#

it wont get the bot online

smoky sinew
#

can you show your code?

#

and error, if there is one?

slate swan
smoky sinew
#

no just here

slate swan
smoky sinew
#

you have to import discord.ext.commands

#

from discord.ext import commands

slate swan
#

this sum i did with a YT tut 😭

smoky sinew
#

sure

slate swan
#

Python way too difficult

smoky sinew
#

you will get better with practice

slate swan
#

ima give up on it, ive tried 5 vids now

#

nun of them helped, each time a new error came

smoky sinew
#

what's the error with that though

#

looks like it should work

drifting arrow
#

🤔 how can I improve the looks of this? loll

#

Too much scrolling. and idk if I want to put 'pages' in

slate swan
#

Only issue is that I need to integrate this into a bot, and add a prefix. Nothing else

#

it works on replit, but not on python

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
drifting arrow
#

Is it possible to force an embed to be 2 columns? not 3 or 4?

smoky sinew
smoky sinew
slate swan
smoky sinew
#
column 1 (inline = False)
column 2 (inline = True)
column 3 (inline = False)
column 4 (inline = True)
slate swan
#

I don’t see anything else working better

smoky sinew
#

i could have still helped

slate swan
#

The one I sent now works too, I just need to integrate it into a bot

smoky sinew
#

what is the error message or how did it not work

slate swan
#

No matter what

forest hatch
#
async def leave(ctx):
    voice_client = ctx.message.guild.voice_client
    if voice_client.is_connected():
        await voice_client.disconnect()
        await ctx.send('Bot left the voice channel')
    else:
        await ctx.send("The bot is not connected to a voice channel.")```
#

can someone help me, my bot can't leave voice channel when the voice channel name contain emoji

smoky sinew
slate swan
shrewd vapor
smoky sinew
#

the code is correct

slate swan
smoky sinew
#

maybe if the old thing worked in replit, try running the new code in replit

slate swan
smoky sinew
#

make what

slate swan
smoky sinew
#

make replit? i don't understand

slate swan
smoky sinew
#

ok

formal basin
#

What does this mean?

smoky sinew
#

don't make the tree manually

formal basin
smoky sinew
#

remove it?

formal basin
slate swan
shrewd vapor
slate swan
shrewd vapor
#
@bot.event
async def on_message_delete(message):
    guild_id = message.guild.id
    if database_log_message.get_channel(guild_id) is None:
        return
    channel_send = database_log_message.get_channel(guild_id)
    if message.author == message.author.bot:
        return
    if message.content == ".verif":
        return
    if message.embeds:
        if message.content is None:
            await channel_send.send(message.embeds)
        return
    embed=discord.Embed(title = f"Message deleted in {message.channel}", description = f"{message.author.name} Message deleted", color=discord.Color.dark_purple())
    embed.add_field(name="Message :",value=message.content, inline=False)
    embed.add_field(name = "Account created :", value = message.author.created_at.strftime('%d %B %Y at %H:%M'))
    await channel_send.send(embed=embed)


@bot.event
async def on_message_edit(message_before, message_after):
    guild_id = message_before.guild.id
    if database_log_message.get_channel(guild_id) is None:
        return
    channel_send = database_log_message.get_channel(guild_id)
    if message_before.embeds:
        if message_before.content is None:
            await channel_send.send(message_before.embeds)
        return
    embed = discord.Embed(title = f"Message edited in {message_before.channel}", description = f"{message_before.author.name} message edited", color = discord.Color.dark_purple())
    embed.add_field(name = "Message Before :", value = message_before.content, inline = False)
    embed.add_field(name = "Message After :", value = message_after.content, inline = False)
    await channel_send.send(embed=embed)```

I really need help please, he don't work with discord.py 2.2.2
smoky sinew
#

what do you mean doesn't work

hushed galleon
#

"not working" is a pretty vague explanation but it seems you said earlier it didnt send any message, so i would suggest using print statements to figure out how far its getting into your event handler

#

also make sure you have the message_content intent enabled since that's new to 2.0

shrewd vapor
#

How to activate it ?

#
intents=discord.Intents.all()```
I have this already
shrewd fjord
shrewd vapor
#

Yes all is activate

shrewd fjord
#

any error?

shrewd vapor
#

No error

shrewd fjord
#

@bot.event
async def on_message_edit(message_before, message_after):

#

is thhis such a thing?

#

!d discord.on_message_edit

unkempt canyonBOT
#

discord.on_message_edit(before, after)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_edit "discord.on_raw_message_edit") event instead.

The following non-exhaustive cases trigger this event...
shrewd fjord
#

ok it is

shrewd vapor
#

Yes

shrewd fjord
#

i was just confused on event name lol

shrewd vapor
#

xD

shrewd fjord
hushed galleon
#

i would suggest using print statements to figure out how far its getting into your event handler
right now we don't know why its not sending a message, there's too many reasons for that

  1. if database_log_message.get_channel(guild_id) is None: return
  2. if message.author == message.author.bot: return
  3. if message.content == ".verif": return
  4. the event handlers never ran because your bot was restarted after the messages were already sent
    ...
shrewd vapor
#

He work now

#

My database is empty for channel log, I have defined and he work

#

How to use discord.ui.Modal.on_submit ?

smoky sinew
#

you simply override it

shrewd vapor
#

How ?

#

You can help me please ?

slate swan
smoky sinew
smoky sinew
#
async for ban_entry in interaction.guild.bans():
slate swan
shrewd vapor
#
@bot.tree.command(name="unban", description="Unban a member")
async def unban(interaction, *, member : str, reason : str):

        if (not interaction.user.guild_permissions.ban_members):
            await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
            return

        banned_users = await interaction.guild.bans()
        member_name, member_discriminator = member.split("#")

        for ban_entry in banned_users:
            user = ban_entry.user

            if (user.name, user.discriminator) == (member_name, member_discriminator):
                await interaction.guild.unban(user)
                embed=discord.Embed(title=f"{user} as been unban", inline=False)
                embed.add_field(name="Reason :", value=f"{reason}")
                embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
                await interaction.reply(embed=embed)```
smoky sinew
#

remove banned_users

#

actually you might not need to add paranthesis at all

shrewd vapor
#
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member : discord.Member, *, reason : str):
    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
        return
    await member.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
    await member.ban (reason = reason)
    await interaction.response.send_message(f"{member.id} has been banned !")```
And for ban ?
smoky sinew
#

what about it

shrewd vapor
hushed galleon
#

Unknown interaction means your command didnt respond in time, discord only gives you three seconds

#

if you need more time, defer and followup: py await interaction.response.defer() ... # do whatever in between await interaction.followup.send("a message")

shrewd vapor
#

How I can ban by id ?

hushed galleon
#

create a discord.Object with the given ID and pass it to Guild.ban()

shrewd vapor
#
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member_id : discord.Object, *, reason : str):
    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
        return
    await member_id.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
    await interaction.guild.ban (member_id, reason = reason)
    await interaction.response.send_message(f"{member_id.id} has been banned !")

Is good ?

smoky sinew
#

or since all User objects implement abc.Snowflake, you can just typehint it as discord.User and pass that instead

shrewd vapor
#
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member_id : discord.User, *, reason : str):
    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
        return
    await member_id.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
    await interaction.guild.ban (member_id, reason = reason)
    await interaction.response.send_message(f"{member_id.id} has been banned !")```
Is good for you ?
smoky sinew
#
@bot.tree.command()
async def unban(interaction: discord.Interaction, user: discord.User) -> None:
    await interaction.guild.unban(user)
#

this should be all you need for an unban command

shrewd vapor
#

Oh

#

Thanks

slate swan
#

@smoky sinew yooo

smoky sinew
#

hi

slate swan
smoky sinew
#

bruh

slate swan
#

?

smoky sinew
smoky sinew
#

did you test it on replit?

slate swan
#

i wrote it fully, and it wouldnt load in on repit

#

its cuz thats a rebirth calculkator

smoky sinew
slate swan
#

Yea but I couldnt get it to wrok cuz it was missing the actual calculator

smoky sinew
#

did you add it?

slate swan
smoky sinew
#

how did it not work?

slate swan
#

everything after that

smoky sinew
#

you shouldn't use input() with a discord bot..

#

just pass it as function arguments

slate swan
#

did u look at the full code?

smoky sinew
#

yeah

#

just change it into a function and use arguments

slate swan
#
discord.Interaction.response.send_message()```
and 
```py
discord.Interaction.followup.send()

aren't working

smoky sinew
#

use your interaction variable

slate swan
#
async def clear(interaction: discord.Interaction, messages:Optional[int]=None, member:Optional[discord.Member]=None):
slate swan
# smoky sinew you need an instance
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
slate swan
unkempt canyonBOT
#
Pasting large amounts of code

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

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

smoky sinew
#

did u have to ping me for that

slate swan
smoky sinew
#

you probably want to do InteractionResponse.defer and Interaction.followup.send

rigid void
#

discord bots can be programmed with python? I had no idea lmao haha

#

what else except python tho

smoky sinew
rigid void
#

That's cool dude thanks

slate swan
rigid void
#

ay thanks

blissful badge
#

How do I make my bot only listen for commands/events/etc in one server?

junior falcon
#

Hey there, im trying to use an emoji in a button but it throws Invalid emoji error. This is my code

button = Button(label=f"{ticketpanelconf['button_text']}", style=discord.ButtonStyle.green, emoji=f":{ticketpanelconf['button_emoji']}:")

and this is the data of button_emoji:

button_emoji: incoming_envelope

Anybody knows how to fix it? The format of the emoji looks good to me

smoky sinew
junior falcon
#

sorry, so what i should use?

slate swan
#

you need to get form like this: !this

#

to get such form you need to place \ before emoji in discord

junior falcon
slate swan
#

No you use it Like this inside discord application

#

If you want a bot to use Emoji you need to give him this format i provided

blissful badge
#
    @commands.command()
    async def embed(self, ctx):
        def check(message):
            return message.author == ctx.author and message.channel == ctx.channel

        await ctx.send('Waiting for a title')
        title = await self.bot.wait_for('message', check=check)
  
        await ctx.send('Waiting for a description')
        desc = await self.bot.wait_for('message', check=check)

        await ctx.send('What channel should I send this in? (please respond with channel id)')
        destination = await self.bot.wait_for('message', check=check)

        embed = discord.Embed(title=title.content, description=desc.content, color=0x1ABC9C)
        embed.set_author(name="SC News Team", icon_url="https://i.imgur.com/MJnM3LU.png")
    
        channel = self.bot.get_channel(destination)
        await channel.send(embed=embed)

trying to get a bit of help with some code.

trying to get it so the user can input the channel id in response to the "await.ctx.send(what channel) prompt but having some trouble getting it to use that channel id

#

any ideas maybe?

smoky sinew
#

you will have to convert it to an integer

blissful badge
#

Oh interesting, not something I have encountered before

smoky sinew
#

well yes, that is because IDs on discords are stored as integers

#

whereas the text of a message can contain anything, therefore it is a string

#

you cannot compare the two (cough cough javascript)

blissful badge
#

Looking at it online but a bit confused how I would use int() in this setting

smoky sinew
#

it would be int(destination.content) as destination is a Message

#

you will probably want to add isnumeric or isdigit to the check too

blissful badge
#

Obviously missing something

smoky sinew
#

a second closing paranthesis?

blissful badge
blissful badge
#

sometimes its the simple things

#

@smoky sinew getting this now

#

Is there something I need to change with

slate swan
smoky sinew
#

you hyave to use it in combination with defer

smoky sinew
blissful badge
#

I did not

slate swan
blissful badge
smoky sinew
#

wait_for.content?

#

wait_for returns Message and you use .content on it

#

so int(dest.content)

blissful badge
#

Oh oh oh

#

I remember us talking about similar items

smoky sinew
blissful badge
smoky sinew
#

can you show your full code

blissful badge
#

wait maybe I reverted something one sec

#

yup that was the case, I had switched channel.send back with ctx.send to test something, i put it to channel.send and it did it right

blissful badge
#

@smoky sinew or anyone who is around to look

here is the entire code

    @commands.command()
    async def embed(self, ctx):
        def check(message):
            return message.author == ctx.author and message.channel == ctx.channel

        await ctx.send('Waiting for a title')
        title = await self.bot.wait_for('message', check=check)
  
        await ctx.send('Waiting for a description')
        desc = await self.bot.wait_for('message', check=check)

        await ctx.send('Please provide me with the image link for this post, if no image is needed just say none.')
        newsimage = await self.bot.wait_for(ctx.message.attachments, check=check)

        await ctx.send('What channel should I send this in? (please respond with channel id)')
        dest = await self.bot.wait_for('message', check=check)

        await ctx.send('Who should I tag?')
        whototag = await self.bot.wait_for('message', check=check)

        await ctx.send('What is the tag preview?')
        tagpreview = await self.bot.wait_for('message', check=check)

        embed = discord.Embed(title=title.content, description=desc.content, color=0x1ABC9C)
        embed.set_author(name="SC News Team", icon_url="https://i.imgur.com/MJnM3LU.png")
        embed.set_image(url= newsimage)
    
        channel = self.bot.get_channel(int(dest.content))
        await channel.send(embed=embed)
        await channel.send(f"@", whototag, " ", tagpreview)

I am running into two issues.

For the image portion where it asks

        await ctx.send('Please provide me with the image link for this post, if no image is needed just say none.')
        newsimage = await self.bot.wait_for(ctx.message.attachments, check=check)

and throws it into the embed like this

        embed.set_image(url= newsimage)
it returns this error 
Traceback (most recent call last):
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'lower'

I guess I will start with the first issue

#

I have a feeling the issue lies in how I am using ctx.message.attachments inside of self.bot.wait_for() but I am unsure of how to proceed

smoky sinew
#

await self.bot.wait_for(ctx.message.attachments)

#

this is the part that's wrong, you must pass an event to wait_for

#

e.g. like wait_for("message") or wait_for("member_join"), things like that

blissful badge
#

got it, so then how would I get it to capture the attachment?

#

or would it theoretically just do it?

smoky sinew
#

if an image is attached, you can just wait for the message event and add a check so that an image must be present

#

then use Message.attachments to access it

blissful badge
smoky sinew
#

what is newsimage though

blissful badge
#
        await ctx.send('Please provide me with the image link for this post, if no image is needed just say none.')
        newsimage = await self.bot.wait_for('message', check=check)
#

@smoky sinew just the identifier name for what goes in the embed

smoky sinew
#

no you would need newsimage.content

blissful badge
#

ahhhhhh

#

lets see if that fixes it

blissful badge
#

it posted the embed with no image

smoky sinew
#

it seems like you're not posting the actual link, but an attachment

#

so the message content in empty

blissful badge
#

yeah I would like to be able to pull it off the attachment

#

Is that even possible?

smoky sinew
#
chosen_image = await self.bot.wait_for("message", check=lambda m: all([
    m.author == ctx.author,
    m.channel == ctx.channel,
    len(m.attachments) == 1
])

embed.set_image(url=chosen_image.attachments[0].url)
#

try this

blissful badge
#

on it

#

Wait, I would retain the await ctx.send so it has a prompt correct?

#

duh ignore me

#

@smoky sinew worked pydis_strong

#

u have achieved god status in my eyes for all the help you've provided btw

smoky sinew
#

nice, glad it works

vital glacier
#

im trying to make a command using the discord.Member.timeout function, but I need to make it so I can use different times of the timeout, up to 28 days

#

anyone got an idea how, cus it uses datetime.timedelta

#

so for instance, if i do ,timeout (user) 1d spamming (third warning), it would time the user out for 1 day and then put the "spamming (third warning) as the reason

smoky sinew
#

check out the pydis duration system

unkempt canyonBOT
#

bot/utils/time.py lines 16 to 24

_DURATION_REGEX = re.compile(
    r"((?P<years>\d+?) ?(years|year|Y|y) ?)?"
    r"((?P<months>\d+?) ?(months|month|m) ?)?"
    r"((?P<weeks>\d+?) ?(weeks|week|W|w) ?)?"
    r"((?P<days>\d+?) ?(days|day|D|d) ?)?"
    r"((?P<hours>\d+?) ?(hours|hour|H|h) ?)?"
    r"((?P<minutes>\d+?) ?(minutes|minute|M) ?)?"
    r"((?P<seconds>\d+?) ?(seconds|second|S|s))?"
)```
smoky sinew
#

this especially is useful

vital glacier
#

uh

blazing flint
#

checking if a user is timed out?

blazing flint
#

I also have another unrelated question and was wondering how I can change the status of my bot

#

*presence

pliant gorge
#

Can somone put a bot on my@server if they click on my@invite

glad cradle
unkempt canyonBOT
#

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

Changes the client’s presence.

Changed in version 2.6: Raises [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.

Example

```py
game = disnake.Game("with the API")
await client.change_presence(status=disnake.Status.idle, activity=game)
```...
glad cradle
#

but don't do this on on_ready events