#discord-bots

1 messages · Page 103 of 1

edgy plinth
#

alr

vocal snow
#

also, you're calling .format on the File and not the string...

vocal snow
#

same way you're setting the callback

#

although you really should subclass instead

edgy plinth
#

how

vocal snow
#

buffer = io.BytesIO()

#

img.save(buffer, format="png")

edgy plinth
#

does it need importing?

vocal snow
#

!d io

unkempt canyonBOT
#
io

Source code: Lib/io.py

sick birch
#

Yes, but I’m pretty sure it’s reset when you load up your replit the next time

paper sluice
slate swan
#

BRO THAT BREAKS TOS

ornate crater
honest shoal
stable path
#

Oh.

limber pagoda
#

I have multiple megabytes worth of json files

sick birch
#

I'm hoping it isn't the latter

limber pagoda
#

I have an economy bot

#

And it stores the days

dense coral
#

view = nextcord.ui.View(timout=0/None)

edgy plinth
#
if content_word == "test" and message.author.id in Admins: 
          map = Update(Faction)
        
          bytes = BytesIO()
          map.save(bytes,format="PNG")
          map.show()
          bytes.seek(0)
          dfile = discord.File(bytes,filename="test_image.png")
          await message.channel.send("{} SHUT THE FUCK UP! {}".format(message.author.mention,file=dfile))

Help i have no clue whats wrong

edgy plinth
sick birch
#

!f-string

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

edgy plinth
# sick birch !f-string
await message.channel.send(f"{message.author.mention} SHUT THE FUCK UP! {file=dfile}") ```like this?
sick birch
#

You need to pass in file as a seperate argument of .send()

#
await message.channel.send(f"...", file=dfile)
edgy plinth
sick birch
#

If it works it works

jade prawn
#

How can I detect when a component has been interacted with (I'm using python3.9)

stable path
#

Pain.

jade prawn
#

well, that would first require reciving the input in the first place.. ties back to my question

#

if you've found out how to do that, please let me know

#

how did you detect when they clicked a button

#

please share an example

#

can you show me an example of how you detected the button press though?

indigo pilot
fading marlin
#

what're your trying to do?

bright wedge
#
    @discord.ui.button(style=discord.ButtonStyle.red, custom_id='one',emoji="🥾",)
    async def one(self, interaction: discord.Interaction, button: discord.ui.Button):
        guild = interaction.guild
        print(guild,interaction.user.id)

Error: None 1023653948123458718
#

why cant find the guild?

indigo pilot
#

most cases i could just do bot.add_view(ReactionRoleView(menu=None, name=None) but since theres a loop right inside the view i cant

fading marlin
#

why can't you?

#

also, you should be using custom IDs with your buttons

indigo pilot
#

that just sets no timeout, not on reload & reboot

indigo pilot
fading marlin
#

oh, right. Why are you passing None in the first place then? And if for some reason that makes sense in your head, pass in an empty list instead of None

indigo pilot
#

and i cant pass a empty list i dont think since the view will be edited to none then

fading marlin
# indigo pilot thats what your supposed to do lol

I wouldn't think so. Apparently, you're trying to make reaction roles with buttons, so I'm guessing menu would be the list of roles, and name would be, perhaps, the name of the guild, idk. You'd probably want to iterate through your "database" (which apparently is a JSON file and you shouldn't use that as a database), get the list of roles that you saved, and pass that to your view. Don't pass None, because you actually need a value

stable path
#

How would one go about adding a cooldown to responses? I’ve tried using the sleep command but it instead delays the response rather than stopping it all together.

fading marlin
#

interaction responses as a whole or slash commands?

indigo pilot
fading marlin
# stable path Yes.

I gave you 2 alternatives, you're giving me a "yes" answer. That doesn't really help

stable path
#

I don’t want the commands to be spammable.

#

Since the environment I plan on implementing the bot a lot of the people in that server jump the bot all at once.

fading marlin
# stable path The first one.

You're gonna have to implement your own cooldown system for buttons and modals. For slash commands though, there's a check:

#

!d discord.app_commands.checks.cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
fading marlin
#

you're welcome

fading marlin
mighty pilot
#

Can someone point me in the right direction to adding an option to a slash command? So if they use /level it shows their level, which I have already written. Or they can do /level: user=<user> to get someone else's level

#

Actually, nvm I think I just found it. We shall see.

mighty pilot
#

Follow up: did not work as intended.

fading marlin
#

you can type hint Optional or add a default value

from typing import Optional
from discord import Interaction


@app_commands.command(...)
async def command(self, interaction: Interaction, argument: Optional[str]):
    ...
# or
@app_commands.command(...)
async def command(self, interaction: Interaction, argument=None):
    ...
# or both
@app_commands.command(...)
async def command(self, interaction: Interaction, argument: Optional[str] = None):
    ...
limber bison
#
 @discord.ui.TextInput(label="About Me" , style= discord.TextStyle.paragraph , placeholder = "Write here")
    async def callback4(self, interaction: discord.Interaction , TextInput):
        if interaction.user != self.ctx.author:
            await interaction.response.send_message(f"Not your interaction" , ephemeral=True)
            return
        self.about_me = TextInput.value
        await interaction.response.send_message(f"**ABOUT ME**\n\n{TextInput.value}" , ephemeral = True) ```

textinput is not callable ?
error ]
fading marlin
#

TextInput is a class you use with modals...?

robust fulcrum
#

@asher suggested me to make a views and interactions manager library for discord.py
I asked him multiple times but he not told what should it do

sick birch
#

there are already plenty of tools that do that

robust fulcrum
#

I will make this type of library for my practice

sick birch
robust fulcrum
#

Like redux in react?

sick birch
#

Might be better to work on something a bit easier and more feasible/useful

limber bison
ember nest
#

What is the problem on this code why not working

upbeat gust
#

not guild.member.count

ember nest
#

Lemme try

ember nest
tired hinge
#

if i have a list of messages i want to delete, which is better - channel.delete_messages() or purge() with a check?

#

by that i mean which is less likely to get me rate limited 💀

hushed galleon
#

depends on how you're getting the messages to delete

#

purge() uses the channel history() to gather its messages, but if your bot already has the message IDs you want to delete, then delete_messages() will likely be the most simple

slate swan
hushed galleon
#

delete_messages() is always a single API call while purge() is at minimum 1 api call, that being querying message history, and any number of api calls afterwards to delete / query more messages

slate swan
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
a+million+dollars

The command works in second try but sometimes it fails and i have to try again to make it work

naive briar
#

If your command has to take over 3 seconds to respond, you have to defer it

#

And requests is blocking. Use aiohttp

slate swan
#

how do i defer it

naive briar
#

What's your library?

slate swan
#

pycord

#

i m using requests in other commands too so i might even defer it

naive briar
#

!d discord.InteractionResponse.defer - You could also use inter.defer. It's the same thing

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
slate swan
#

hmm got it

#

ty

zinc phoenix
#

Hello guys, I'm thinking of writing unit tests for my discord bot, but when I run the programme, it returns "TypeError: monthrn() missing 1 required positional argument: 'ctx'"
Here's the code:

import unittest
from unittest import IsolatedAsyncioTestCase
from datetime import datetime
import pytz
from cogs.time_cmds import TCmd


class TestTime(IsolatedAsyncioTestCase, TCmd):

  async def test_month(self):
    month = await TestTime.monthrn("monthrn")
    await self.assertEqual(
      month,
      datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).strftime("%m"))


if __name__ == '__main__':
  unittest.main()

Can anyone help? Thanks.

rugged shadow
#

tests for a discord bot?

#

and we also don't know what monthrn is

zinc phoenix
#

Oh, sorry

#

It's a command that shows you the month as of now

#

I'm trying to writing a test case to see if it returns the right month

rugged shadow
#

so monthrn is actually a Command?

#

you will need to write a custom Context

zinc phoenix
#

I see

#

By using discord.ext.commands.Context?

rugged shadow
#

you'd need to subclass that, yes

zinc phoenix
#

Alright, thanks

zealous pike
#

direct = input("is the flight direct?: ")
flight1 = input("Is flight1 direct?: ")
flight2 = input("Is flight2 direct?: ")

direct: str(input("Is the trip direct or transit?: "))
flight1 = str(input("Please enter direct or transit"))
flight2 = str(input("Please enter direct or transit"))
flight3 = str(input("Please enter direct or transit"))

if flight1: ("direct")
print("flight1 is suitable for you")
if flight2: ("direct")
print("flight2 is suitable for you")
else:
print("flight3 is suitable for you")

low cost

cost: str(input("Is the flight cheap?: "))
flight1 = str(input("Please enter cheap or expensive"))
flight2 = str(input("Please enter cheap or expensive"))
flight3 = str(input("Please enter cheap or expensive"))
if flight1: ("cheap")
print("flight1 is suitable for you")
if flight2: ("cheap")
print("flight2 is suitable for you")
else:
print("Flight3 is suitable for you")

short time

Time: str(input("Is time long or short?: "))
flight1 = str(input("Please enter short or long"))
flight2 = str(input("Please enter short or long"))
flight3 = str(input("Please enter short or long"))
if flight1: ("short")
print("flight1 is suitable for you")
if flight2: ("short")
print("flight2 is suitable for you")
else:
print("flight3 is suitable for you")

#

I just want to tell you the idea of the project. I supposed to create a program for people who want to travel and there are three flights at the same time. The user must choose the best option in duration of flight, ticket price and if it is direct or transit. After he choose the program will suggest the best flight for him based on the options that he chose. Note: I have to use if nested in my code

zinc phoenix
rugged shadow
#

just *args and **kwargs, pass that into super().__init__()

#

i think you just have to override ctx.send and/or ctx.reply

slate swan
#

how do i sync commands in pycord?

naive briar
#

It's auto-sync

zinc phoenix
#

Sorry, Im still new to programming

slate swan
naive briar
upbeat gust
#

that's a really broad question

#

What leaderboard? Wdym global? What does it do right now?

#

So how does your leaderboard work

#

In your code

#

the names in the brackets are the guild names

Not just the best players in 1 server

#

but you already have people from different servers..?

#

so what's the problem

#

you want X, but X already happens

#

you said you want ppl from different servers, but that's already what's happening is it not?

#

Oh this isn't yours?

#

ah

#

ok well how does yours work, codewise

#

Is it getting these from a db or?

#

I don't even know what this game is I can't guess what columns you need

You just need what you want to store

#

If this isn't connected to a db then where are you getting this data?

#

don't store names when you can store ids, names change

#

Yes

#

you'd use get_user

#

have you chosen a db?

#

From the discord.py server:

TL;DR: MySQL is a bad database. Don't use it unless you have literally no other option.

Why shouldn't I use MySQL?

  • MySQL has no transactional DDL. This means that if you fuck up creating a table in the middle of a migration, you cannot rollback easily.
  • MySQL has a lot of security issues. New zero-day vulnerabilities are found regularly.
  • MySQL is owned by Oracle.
  • MySQL is slow. It beats Postgres etc at some things, but once you move beyond basic queries it begins to slog.
  • MySQL disconnects you randomly. Unless you setup your connection specially, it will break regularly.
  • MySQL allows all kinds of insane data to be inserted. '0000-00-00' is valid in MySQL.
  • MySQL is not ANSI compliant. You have to turn it on; even then it isn't fully compliant.
  • MySQL has no feature advantage over other databases; PostgreSQL has many more useful features (such as RETURNs).

There is no reason to use MySQL over PostgreSQL, or even sqlite3. See also:
https://blog.ionelmc.ro/2014/12/28/terrible-choices-mysql/
https://grimoire.ca/mysql/choose-something-else

slate swan
#
  • mysql is owned by oracle
    how about Java and javascript
#

don't see any reason to not use mysql with a bot. unless you're doing some high-fi operations that only pgsql supports

#
  • mysql disconnects ....

skill issue, use a connection pool, not direct connections

upbeat gust
#

Nope

slate swan
#

whats the issue?

upbeat gust
#

Find an async library for it and look at docs/examples

slate swan
#

the first thing you'll do is choose your driver
for async context you can use aiomysql or async with sqlalchemy ( relatively hard)
next you'll create a connection pool with the credentials of your host
later create the table with columns you need

#

!pip aiomysql

unkempt canyonBOT
upbeat gust
#

I mean it's your game, store whatever you need but that looks good

slate swan
#

are you using a connection or a pool?

#

seems all set then, simply create ur table and proceed now.

upbeat gust
#

You should decide if you want to have a composite pk of guild and user or just the user as a primary key

slate swan
#

sure ping me when you need help

#

vs code keeps giving me indentation error

#

i don't anything wrong with the code

#

@slate swan

slate swan
#

yeah

#

mind showing that code?

#

i have a question

#

why does my cmd promt keeps repeating and iteration

#

that has already been done

#

if i add a licensing system

#

at the top of code

slate swan
#

im assuming its because of the if __name__ == '__main__':

slate swan
#

this is the code being repeated

slate swan
slate swan
#

which one

#

this is desirable

slate swan
#

this is repeated

slate swan
slate swan
#
@bot.command()
async def prison(ctx, member: discord.Member = None, time = None, *, reason = None):
    prison_role = discord.utils.get(ctx.guild.roles, name="Prison")
    author = ctx.message.author.id
    time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
    if member == None:
        await ctx.send("Please Mention A Member To Prison Him!")
    elif time == None:
        await ctx.send("Please Mention The Time You Want To Put!")
    elif reason == None:
        reason = "None"
    tempmute = int(time[:-1]) * time_convert[time[:-1]]
    embed = discord.Embed(title="Prison Member", description=f"{member.mention} Is In Prison. For {time}")
    await member.send(embed=embed)
    await ctx.send(embed=embed)
    await member.add_roles(prison_role)
    await asyncio.sleep(tempmute)
    await member.remove_roles(prison_role)

when i do !prison @slate swan 20m dhsu

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '20'```
stable path
#

How would I get a bot to scan a predetermined channel ID?

#

So I can set it as a parameter for an if statement.

#

No that doesn’t work.

naive briar
stable path
#

The idea is to get it to only be able to respond in a predetermined channel based on its channel ID.

#

But I’m not sure what the library call is.

#

Or it if even exists.

slate swan
#

like for me it works

slate swan
#

okay

slate swan
stable path
slate swan
stable path
# slate swan Oh.\

Thanks anyways though it was worth a shot and besides I learned something from it.

slate swan
slate swan
# slate swan send the complete error log not just the commandinvokeerror

[2022-10-09 10:48:59] [ERROR ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 487, in prison
tempmute = int(time[:-1]) * time_convert[time[:-1]]
KeyError: '20'

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

Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 165, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '20'

#

ok gimme a min let me try it

#

okay tysm

naive briar
#

What's the problem

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
stable path
naive briar
#

Then what's the problem with that part

#

I don't know what you want, and that's not something I can help with

slate swan
#
@bot.command()
async def prison(ctx, member: discord.Member = None, time = None, *, reason = None):
    prison_role = discord.utils.get(ctx.guild.roles, name="Prison")
    author = ctx.message.author.id
    time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
    if member == None:
        await ctx.send("Please Mention A Member To Prison Him!")
    elif time == None:
        await ctx.send("Please Mention The Time You Want To Put!")
    elif reason == None:
        reason = "None"
    tempmute = int(time[:-1]) * time_convert[time[:-1]]
    embed = discord.Embed(title="Prison Member", description=f"{member.mention} Is In Prison. For {time}")
    await member.send(embed=embed)
    await ctx.send(embed=embed)
    await member.add_roles(prison_role)
    await asyncio.sleep(tempmute)
    await member.remove_roles(prison_role)

when i do !prison @slate swan 20m dhsu

[2022-10-09 10:48:59] [ERROR   ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(args, **kwargs)
  File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 487, in prison
    tempmute = int(time[:-1]) time_convert[time[:-1]]
KeyError: '20'

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
    await coro(args, **kwargs)
  File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 165, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '20'```
naive briar
slate swan
naive briar
#

You can't do for anything

slate swan
#

what

naive briar
#

You're removing m from the string then try to get it

#

Where did you get these from

slate swan
#

so to remove the m?

slate swan
slate swan
#

this should be the correct tempmute line and btw small tip but change the rest of the part like the dm stuff and all, maybe put it after the member is awarded with the role

naive briar
#

!e

time = "20m"

print(time[1:])
print(time[-1:])
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0m
002 | m
slate swan
#

doesnt work

slate swan
#

i just corrected the line

slate swan
#

like

#

okay

slate swan
#
@bot.command()
async def mines(ctx, amount=None):
    amount = int(amount)
    if amount is None:
        await ctx.reply('Must specify a value between 1-24\nExample: ``.mines 5``')
    elif amount <= 24:
        mines = 25*[':question:']
        random_safe = random.sample(mines, amount)
        for x in random_safe:
            random_safe[x] = ':gem:'
        row1 = mines[0] + mines[1] + mines[2] + mines[3] + mines[4]
        row2 = mines[5] + mines[6] + mines[7] + mines[8] + mines[9]
        row3 = mines[10] + mines[11] + mines[12] + mines[13] + mines[14]
        row4 = mines[15] + mines[16] + mines[17] + mines[18] + mines[19]
        row5 = mines[20] + mines[21] + mines[22] + mines[23] + mines[24]
        percentage = str(random.randint(45, 90))
        thumbnail = 'https://cdn.discordahttps://media.discordapp.net/attachments/1017329425513197568/1028582459941584978/E6998A39-624D-45C2-9002-B27FD399A776.jpg?width=1041&height=1055pp.com/attachments/1013865134504026112/1015741200722055289/standard.gif'
        em = discord.Embed(color=0x11F1D3)
        em.set_thumbnail(url=thumbnail)
        em.set_footer(text="Made by Dewier")
        em.add_field(name="Mines predictor",value=row1 + "\n" + row2 + "\n" + row3 + "\n" + row4 +"\n" + row5 + "\n" + "**Accuracy**" + "\n" + percentage +"%")
        await ctx.reply(embed=em)
    else:
        await ctx.reply('Must specify a value between 1-24\nExample: ``.mines 5``')```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

tired hinge
#

with delete_messages(), do i need to pass message objects or message IDs?

naive briar
unkempt canyonBOT
#

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

Deletes a list of messages. This is similar to [`Message.delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.delete "discord.Message.delete") except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

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

what do you want to do though?

tired hinge
slate swan
#

await channel.delete_messages(discord.Object(id=1234))

slate swan
slate swan
#

you don't even need a discord.Object tbh, any object which has an id attribute set as the message id works

#
import random
amount = 5
mines = 25*[':question:']
random_safe = random.sample(mines, amount)
for x in random_safe:
  mines[x] = ':green_square:'
print(mines)
print(f'\n\n\n{random_safe}')```
#

my bad, i used the wrong method above xd

#

TypeError: list indices must be integers or slices, not str help pl

slate swan
#

yeah im high don't mine me

#

*mind

slate swan
slate swan
#

what do you want to do?

slate swan
feral frost
#

how can i make a command that shows how many users are in all the servers my bot is in ? i tried len(bot.users) but that doesnt work

feral frost
vocal snow
#

random numbers? such as?

feral frost
feral frost
vocal snow
feral frost
vocal snow
#

your full command

feral frost
vocal snow
#

and your member intents are enabled?

feral frost
#

idk

vocal snow
#

?? how do you not know what intents you've enabled

feral frost
feral frost
slate swan
#

you just need to enable the intents

feral frost
#

it is enabled

#

even in my code

#

using intents.members = True

feral frost
feral frost
slate swan
# feral frost show me the code
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()

token = os.environ['TOKEN']
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents=intents)

@bot.event
async def on_ready():
    print(len(bot.users))
bot.run(token)
feral frost
#

k

feral frost
rugged shadow
feral frost
#

yes

slate swan
# feral frost ye it works if i print it but i cant use it in a command
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()

token = os.environ['TOKEN']
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(intents=intents)

@bot.event
async def on_ready():
    print(f'{bot.user} is logged in!')
    
@bot.command()
async def countm(ctx):
    await ctx.reply(len(bot.users))
bot.run(token)
feral frost
#

first didnt work but after some time it did

slate swan
#

skill issue

feral frost
#

the first never works

slate swan
#

like seriously how come it works for others and not you?

feral frost
slate swan
#

e

rugged shadow
#

too bad

feral frost
#

lol

slate swan
#

looks like discord isnt installed ig

#

check for any duplicate forks of dpy in your modules and install dpy

#

it should work then maybe reinstall pycord

#

u used an interaction as an input type for your slash command option

tame moth
slate swan
#
 elif risk = 'low':
09.10 10:19:09 [Bot] ^
09.10 10:19:09 [Bot] SyntaxError: invalid syntax```
upbeat gust
#

its a fairly advanced lib and not for beginners

slate swan
naive briar
#

!d discord.Client.user.avatar

#

😿

#

!d discord.Client.user

unkempt canyonBOT
naive briar
#

Just get avatar from it

upbeat gust
unkempt canyonBOT
#

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

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

whats ctx.user 🤨

slate swan
#

pycord moment'

short silo
#
await ctx.edit_original_response(view=self,embed=embed)
#

is this wrong after a button click ?

Traceback (most recent call 
last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "e:\Python Projects\Top War Unity Bot\Commands\Credits.py", line 62, in callback1
    await ctx.edit_original_response(view=self,embed=embed)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 461, in edit_original_response
    data = await adapter.edit_original_interaction_response(
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
slate swan
#

ctx.interaction.original_message ig

upbeat gust
#

You only have 3 seconds

short silo
patent wagon
#

If I give my discord bot to somone to host and they start using it maliciously, if I change the token in Discord Developer Portal will they be able to still use it?

slate swan
#

Are there any legit free alternatives for heroku?

#

Where i can host my bot

naive briar
#

No

slate swan
#

What would you recommend?

#

Okay

silk fulcrum
slate swan
#

interaction.interaction.original_message
because you call your ApplicationContext as interaction. be consistent with names.

slate swan
#

error?

regal heron
#

Hey ! I just used "py -m pip install discord.py", in terminal it says that it is installed but it doesnt seem to work

#

What can I do ? 🤔

slate swan
#

how many versions of python do you have

regal heron
#

1

#

I just installed pycharm on this laptop

#

3.9

slate swan
#

you're using an venv to run the file, did you install discord.py in the venv?

regal heron
#

I just ran that command in terminal, nothing else. It usually worked like that

mighty pilot
naive briar
#

It's lower case b for the button decorator

#

!d discord.ui.button

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
slate swan
#

How do you

#

how do you uhh

#

I'm not sure how to describe it

#

how do you layer the buttons? Like you have one button on top of the other

#

instead of them having the normal layout of moving it to the right?

slate swan
#

you use rows ( row kwarg in Button )

#

And how can I do that?

#

Nvm, figured it out. Thanks guys

#

Is it possible to make a button, but it doesn't do anything, and it's not clickable?

naive briar
#

Disable it

slate swan
#

thanks.

#

u can use ctx.me to represent the client
so it will be something like this ctx.me.display_avatar.url

#

Is it possible to leave a button blank?

#

No label?

slate swan
#

Does that offer a free tier?

slate swan
naive briar
slate swan
naive briar
#

Set \u200b as the label

slate swan
#

tysm

slate swan
#

Yay it works!

#

Tysm catgal.

#

Is that unicode for a space?

slate swan
naive briar
#

Zero-width character

slate swan
#

mmm okay, thanks.

#

but railway.app does have a free tier with $5 credit per month the only setback is you have only 500 execution hours a month

slate swan
#

Okay

#

for railway.app you can either link a card to remove that limit or wait for the github student integration update and get a github student account and apply for that

slate swan
#

How does this look?

slate swan
# slate swan Git hub is launching a vps ?

uh no i meant that you can wait for railway.app to launch an update which allows github accounts with student priviliges to bypass all limits, you will need a github student account tho for it

slate swan
#

Hmm okay

slate swan
#

😉

naive briar
#

The button callback must have 2 parameters (or 3 including self)

slate swan
#

How do i get a person's icon url?

naive briar
#

First for interaction, second for the button

slate swan
#

Tourner dans le vide, vide
Tourner dans le vide, vide
Tourner dans le vide, il me fait tourner

slate swan
slate swan
naive briar
#

Normally what?

#

If it gives you an error

#

It's not

slate swan
#

❤️

#
class Accepte_Button_View(discord.ui.View):
    def __init__(self, timeout = None):
        super().__init__(timeout=timeout)

    @discord.ui.button(label="Accepter la commande", style=discord.ButtonStyle.green, custom_id="Accepte_Button")
    async def callback(self, interaction:discord.Interaction, button: discord.ui.Button):
        if interaction.user.get_role(1014964643191607387):
            Embedvendeuraccepte = discord.Embed(title="Commande prise en charge", description=f"**Vendeur :** {interaction.user.mention}", color = 0xfae893)
            await interaction.response.send_message(embed = Embedvendeuraccepte)
            self.children[0].disabled = True
            await interaction.message.edit(view = self)
        else:
            await interaction.response.send_message("Tu n'es pas un vendeur Java pour accepter la commande. :(", ephemeral=True)

@slate swan

naive briar
#

The self is representing the class

#

It doesn't count as an argument

naive briar
slate swan
#

wrong cht

naive briar
#

Yes

slate swan
#

npnp

#

Is there any way I can make this look more appealing? Also the colors may look bleak because I have Night Light Mode on at 90% strength so ignore that.

slate swan
slate swan
#

Then the flushed emoji grows

slate swan
#

I am trying to make everything more modular and more organized

dull terrace
#

I maintain that using pillow is the way to go

slate swan
#

It scares me, it's intimidating

#

Also your salt miners is very cool

dull terrace
#

It's not as hard as it looks

short silo
#

How to get full input/larger input through a command

slate swan
dull terrace
slate swan
short silo
dull terrace
slate swan
dull terrace
#

Like a string input?

short silo
dull terrace
#

For a slash command?

short silo
dull terrace
#

If you need more than 45 characters I would recommend using a modal

#

Idk how it's getting cut off if you're using message content commands though

short silo
supple ridge
#

i have a question can anyone help?

#

in an exe file the task in if name == main is being looped again and again

#

nothing else is being executed

#

any reasons??

rocky trench
#

We don't have any code, we can't help

supple ridge
#

ah okey I'll send some snippets

#

First Ss :- The code Itself
Second Ss - How it looks in a py file (works perfectly fine)
Third Ss :- How it looks in an exe file (repeats The Enter your license iteration)

#

@rocky trench

ruby valve
#
@tasks.loop(seconds=180)
async def check_activity(ctx, member: Member, client):
    print("checking statuses")
    role = client.guild.get.role(1014853981752795217)
    for member in client.get_all_members():
      if 'cpr' in member.activity:
        await member.add_roles(role) 
        print(f"{member.name}#{member.discriminator} is repping")```

trying to make a bot that automatically gives a user a role if they have "cpr" in their status. I dont get any error but this code doesnt work any help would be appreciated
rocky trench
unkempt canyonBOT
#

property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
fading marlin
naive briar
supple ridge
#

oo

slate swan
#

any ideas why i getting 400 error>?

fading marlin
#

full traceback?

primal token
supple ridge
#

yea it loops

primal token
#

That's odd

supple ridge
#

mhm

primal token
#

If you have and it still has that behavior, I'm not sure, I've never encountered the issue really

supple ridge
#

i havent can u tell

primal token
supple ridge
shrewd apex
#

👋

glad cove
#

hey i need a bot that gets everyone's id inside of a server really fast

#

someone hacked the person that created the server

rare echo
glad cove
#

pretty sure the hacked already changed his password or smth

vocal snow
#

what are you going to do with their ids tho

glad cove
#

invite them to a new server

slate swan
#

bruh

vocal snow
#

you can't just send an invite link in a channel?

slate swan
#

not 100% of the people will join the new server or even have their dms open

#

unless you did something like what restorecord protected servers do, they take the members authorization to auto add them in a new server incase current is nuked

#

but its prolly too late now

glad cove
#

wdym with restorecord protected servers?

rare echo
#

built around your current issue

slate swan
# glad cove wdym with restorecord protected servers?

well there is a bot restorecord which just asks a new member which joins a server to verify by giving their authorization to the bot's application to auto add them in a new server incase the current one is nuked/destroyed

sick birch
#

message.author.roles to get all the roles of the person who sent that message

#

You only passed in 2 values but there are 3 %s

#

Also shouldn’t you be using aiosqlite’s ? Instead of %s?

#

To avoid SQL injection attacks?

rare echo
sick birch
rare echo
slate swan
#

is it actually cloning ?

#

cause if it’s not cloning anything then output would be none

#

also check if that function even returns a channel

#

where is the code that is using the output variable? is it in the same function?

#

that’s why

#

You defined Output in a completely different function

#

is there a specific reason for you storing the channels tho?

#

otherwise if so you need to rethink your logic

#

no like why tho, why are you storing that data? is it explicitly necessary to

#

if you do not need that data I wouldn’t store it. if you need it, then go back to your code and rethink your logic

#

I would suggest creating the temp channels when they join the join2create channel rather than having them use a command

ionic garden
#

i have a hybrid command

#

how should i have the user be able to pass a time argument

slate swan
#

how to fix

shrewd apex
unkempt canyonBOT
shrewd apex
#

ask them to enter a string

ionic garden
#

is that how everyone else does it?

shrewd apex
#

yeah

#

well atleast thats how i do it

shrewd apex
slate swan
#

!pip time-str

unkempt canyonBOT
slate swan
#

im not able sync commands (py cord)

ionic garden
slate swan
#

you just need to do ```py
async def command(ctx, argument: time_str.IntervalConverter):

hushed coral
#
await ctx.author.timeout(until=discord.utils.utcnow() + datetime.timedelta(seconds=20))
#

Am I doing something wrong?

naive briar
#

You got an error?

ionic garden
#

btw does this follow conventions for project organization?

hushed coral
slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
naive briar
#

Oh yeah

slate swan
#

its a positional arg

#

yeah but that would produce some sort of error no?

hushed coral
# unkempt canyon
await ctx.author.timeout(until=datetime.timedelta(seconds=20), reason=None)
slate swan
#

bad on_command_error moment

hushed coral
slate swan
#

also, if you have an on_command_error event add else: raise error to it

#

error being your exception class

hushed coral
slate swan
#

basically yes

hushed coral
#

ye idk still dont work

#
await ctx.author.timeout(datetime.timedelta(seconds=20), reason=None)
shrewd apex
slate swan
#

im using py cord and my slash commands aren't syncing in all the servers

slate swan
slate swan
# slate swan yeah

ok before everything, try syncing the commands after the bot has started
basically add that await client.sync_commands thing in on_ready or something

slate swan
#

you sure? you call load_commands before client.run() !?

slate swan
#

im talking about the sync_command inside your load_commands function, that shouldn't be there

slate swan
#

so this is what ur code looks rn?

slate swan
slate swan
#

just the line 280

#

also, what version of pycord are you using?

#

done

#

2.2.2

#

please try running the code now

#

so the error got fixed

#

what does register_commands return?

#

i mean what does the docs say about that

#

it registers all the commands of given list

#

Register a list of commands.

broken granite
#

does any1 know how to fix his error? AttributeError: 'Message' object has no attribute 'autor'

rare echo
#

author not autor

broken granite
#

oh am stupid af

rare echo
#

haha no worries

slate swan
#

i have 3 commands now and non of them are getting syncing

#

i can only use them in debug_guild server

slate swan
#

@slate swan

slate swan
broken granite
#

import discord

token = ""

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

@client.event
async def on_ready():
print(f"Bot logged in as {client.user}")

@client.event
async def on_message(msg):

if msg.author != client.user:
    if msg.content.lower().startswith("!hi"):
        await msg.channel.send(f"Hi, {msg.author.display_name}")

client.run(token)

for some reason the bot doesn't say anything back

naive briar
unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

sick birch
#

You need to await aiohttp.request

#

It'd be better if you extracted things into their own variables

#
res = await aiohttp.request(...)
content = res.content

# use content here
dull terrace
#

is this an intriguing opening message for someone who uses my game bot for the first time 7739monkathink

rare echo
dull terrace
#

maybe shove a image of a walkie talkie in the corner as an icon but idk how to "break up" the text some more

sick birch
dull terrace
#

idk italics and bold doesn't look right

#

could do something more like this

ionic garden
#

so, a lot of my functions are like this:

#
        try:
            pass
        except discord.Forbidden:
            pass
        except discord.HTTPException:
            pass
```is there a way to use a decorator to have a write once, use everywhere kinda thing?
mental hollow
ionic garden
#

so uh
is there a way to display this error to the user

#

context:

    @commands.hybrid_command(name="mute", aliases=["timeout"])
    @commands.has_permissions(moderate_members=True)
    async def mute(self, ctx: commands.Context, user: discord.Member, time: str):
fading marlin
#

use an error handler

velvet tinsel
unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

ionic garden
fading marlin
#

no, you can have a global error handler

velvet tinsel
#

I advise you use error handlers for specific functions (like kick, ban, timeout etc)

winged coral
#

Global handlers get passed the command object through context

#

I prefer checking the signature there if I want to handle them seperately

#

Less registering callbacks, not really a difference but less messy

verbal hawk
#

Hi, any idea of why would I get this error:
object has no attribute 'flatten'

I have numpy imported, I learnt python a long time ago and as I remember flatten() is in numpy

The actual line looks like this:
users = await new_message.reactions[0].users().flatten()

fading marlin
#

flatten method has been removed and replaced with async iterators

#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
verbal hawk
fading marlin
#

there's an example in the docs

winged coral
#

You can flatten it with an async list comp

verbal hawk
cinder nacelle
#
    code = discord.ui.TextInput(label="Enter The Code", placeholder="Enter The Code Given To You!")
    async def on_submit(self, interaction: discord.Interaction):
        code2 = self.code.value
        with open("collabs.csv", newline="") as csvfile:
            reader =  csv.reader(csvfile, delimiter=" ", quotechar="|")
            for row in reader:
                if row[1] == code2:
                    await interaction.response.send_message("Your code is correct, adding you to the channel!", ephemeral=True)
                    channel = f"🤝| {row[0]} | {row[2]}"
                    await channel.set_permissions(interaction.user, view_channel = True, read_message_history = True, send_messages=True, add_reactions = True)
                else:
                    await interaction.response.send_message("Your code is either wrong or your to late :(", ephemeral=True)

class HisModal(discord.ui.Modal, title="New Collab Form"):
    project_name = discord.ui.TextInput(label="Project Name", placeholder="What is the name of the project?")
    secret_code = discord.ui.TextInput(label="Secret Code", placeholder="For Ex. 50 WL for Okay Bears --> okaybears50")
    spots = discord.ui.TextInput(label = "WL Spots", placeholder="How many WL spots are we giving them?")
    async def on_submit(self, interaction: discord.Interaction):
            
                collab_category = bot.get_channel(1027715302986878996)
                collab = await collab_category.create_text_channel(f"🤝| {self.project_name} | {self.spots}")

                with open('collabs.csv', 'a', newline='\n') as csvfile:
                    writer = csv.writer(csvfile, delimiter=" ", quotechar='|', quoting=csv.QUOTE_MINIMAL)
                    writer.writerow([self.project_name.value, self.secret_code.value, self.spots.value, ])
                
                await interaction.response.send_message("Succesful Newcollab!", ephemeral=True)```
cinder nacelle
winged coral
#

The channel object is a string and not actually a channel object

#

I don't have time to read your code though

#

Oh nvm I see it

cinder nacelle
winged coral
#

It's an f string in your code

verbal hawk
# fading marlin there's an example in the docs

Am I supposed to additionally import anything? I'm using the example line:
users = [user async for user in reaction.users()]

I get the error:

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

winged coral
#

!d discord.Interaction.channel

unkempt canyonBOT
winged coral
#

You can access channel from the interaction directly

winged coral
#

It just doesn't exist at that code point

cinder nacelle
winged coral
#

I can't do all that for you. If you have specific issues I can help

#

Like I said before, your channel object is just a regular string

#

You can access the actual object using the property of Interaction

cinder nacelle
winged coral
#

No you're good don't worry

cinder nacelle
winged coral
#

You don't need to fetch the channel using an ID in this case

#

You can use the interaction object you receive through the callback which sets the channel property for you

verbal hawk
winged coral
#

You're not setting a specific variable for a reaction

#

You're accessing the list via the message object

cinder nacelle
verbal hawk
winged coral
#

Of course

cinder nacelle
#

i think you can just do interaction.user if i am not wrong

north escarp
#
    @commands.slash_command(name = 'verify', description="Пройти верефикацию. \n Пример: /verify")
    async def __verified__(self, interaction: discord.Interaction):

        if interaction.id == 559118900751761418:
            embed = discord.Embed(description = '...', colour=0xF1C40F)
            await interaction.response.send_message(embed=embed)
            return
        view = MyView(interaction)
        embed = discord.Embed(description= f'**...**', colour=0xF1C40F)
        await interaction.response.send_message(embed=embed, view=view, delete_after=60)
        view = await view.wait()

how to make a check so that if the author of the team has a role , then he cannot prescribe a command ??

ionic garden
fading marlin
north escarp
#

how to make a check so that if the author of the command has a role , then he cannot use the command ??

fading marlin
#

check interaction.user.roles

cinder nacelle
#

np

ionic garden
fading marlin
#

sure

slate swan
#

don't do what you are doing rn tho

#

make sure to raise unhandled error so you get to know what the reason behind error wss

ionic garden
#

bruh

#

for some reason

#

the handler in this cog also handles errors coming from other cogs

fading marlin
slate swan
#

is that new?

#

!d discord.ext.commands.Cog.cog_command_error

unkempt canyonBOT
#

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

A special method that is called whenever an error is dispatched inside this cog.

This is similar to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") except only applying to the commands inside this cog.

This **must** be a coroutine.
slate swan
#

seems nice

ionic garden
#
    @commands.Cog.listener()
    async def cog_command_error(self, ctx: commands.Context, e: commands.CommandError):
        await ctx.reply("An unexpected fun error occurred!", ephemeral=True)
#

oh no

fading marlin
fading marlin
slate swan
ionic garden
#

oh bruh

rare echo
#

or would you have to redirect the cog error to that

fading marlin
#

that's the beauty of listeners :p

ionic garden
#

anyway to register an event inside of a class

#

^ or is this the intended way

fading marlin
#

you can do that, or override on_command_error in your bot subclass

#

also, don't sync in setup_hook/on_ready. It can rate limit you quite quickly

patent wagon
#

can somone log into my Discord dev portal using my bot token

fading marlin
#

no

patent wagon
fading marlin
#

they can do stuff with your bot (log in to your bot and bring havoc (probably))

patent wagon
#

is there any way to somnehow lock a file in wich token will be stored

north escarp
#

how to make a check so that the command can be used only in one chat ??

slate swan
#

!custom-check

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

slate swan
#

exactly what u need

limber ocean
#

Can somebody give me some code for a simple discord bot with a function of your choice?

north escarp
#

@slate swan is there something more understandable?

#

how to make a check so that the command can be used only in one chat ??

sick birch
#

You need to convert the response object into a JSON first

#

Use await response.json()

north escarp
#

@sick birch how to make a check so that the command can be used only in one chat ??

sick birch
#

Then you can subscript the resultant dict

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

sick birch
#

@north escarp ^^^

north escarp
sick birch
#

You need to create the predicate first

#

You can also modify the predicate a little bit so it only accepts one ID

north escarp
#
from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)```
stop it needs to be written in a separate class from the commands or what ?
sick birch
#

it can even be top level if needed

ionic garden
ionic garden
#

how do i take in a discord channel as an argument

sick birch
#

You can mention the channel or provide it's ID

ionic garden
#

wb other channels?

#

do i have to consider all these things as well?

sick birch
# ionic garden

A typehint of discord.TextChannel would only try to convert text channels, other types will error

#

If you want to consider the other types you can use the typing.Union[]

ionic garden
#

should i though

#

context: making a lockdown command

sick birch
#

No, only typehint the ones your command should work on

#

E.g if your command sends a message to another channel, a text channel would be appropriate

#

If your command joins the bot into a VC, a VoiceChannel typehint would be appropriate

sick birch
ionic garden
#

uh

#

didn't python recently introduce using the pipe operator
as well?

sick birch
#

If you're on that version feel free to use it

#

I just mentioned the union because I know not everyone is on that version

fading marlin
ionic garden
#

that seems kinda hacky?

upbeat gust
#

How is it hacky?

ionic garden
#

i mean i should implement a check for if the user is a dev, right?

upbeat gust
#

Yes

ionic garden
#

so a if ctx.author.id is in [asdf]?

upbeat gust
#

No is, just x in y

ionic garden
#

yeah had a lapse

ionic garden
slate swan
#

can you show your code?

ionic garden
#

just uh

#

t.Union[discord.TextChannel, discord.ForumChannel]

#

in a type annotation

fading marlin
#

weird...

#

works on my machine 🤔

ionic garden
#

full traceback here

    @commands.hybrid_command("lockdown")
    @commands.has_permissions(manage_channels=True)
    async def lockdown(
            self, ctx: commands.Context,
            channel: discord.TextChannel | discord.ForumChannel = None, time: str = None
    ):
stable path
#

How would I get my bot to accept input from a user?

#

Cause I know how to accept input from the command line but idk how to do it from discord.

fading marlin
ionic garden
#

same error 😦

median flint
#

Alright so I'm making a discord bot for the first time in quite a while, and I'm already stuck

client = commands.Bot(command_prefix= [">"])```
This is giving me an error while I'm trying to create the bot
fading marlin
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
fading marlin
fading marlin
ionic garden
#

just ran pip upgrade, now it's 2.0.0

median flint
fading marlin
#

you gotta pass in intents too

median flint
#

elaborate please, I didn't used to have to do that and have no clue what that means

slate swan
#

i keep getting a indentationerror on if msg.author != client.user: if msg.lower().startswith("?hi"): await msg.channel.send(f"Hello, {msg.author.display_name}") anyone know why?

ionic garden
#

what's the full traceback?

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

fading marlin
#

you should be able to solve indentation errors by yourself, it's basic python

slate swan
# ionic garden what's the full traceback?
    if msg.lower().startswith("?hi"):
    ^
IndentationError: expected an indented block
[Finished in 187ms with exit code 1]
[cmd: ['python3', '-u', '/home/_sakai/learning/discord_bot.py']]
[dir: /home/_sakai/learning]
[path: /usr/local/sbin:/usr/local/bin:/usr/local/games:/usr/sbin:/usr/bin:/usr/games:/sbin:/bin]```
ionic garden
#

maybe indent everything w/ 4 spaces instead?

slate swan
#

lemme try

#

worked thank you.

stable path
# unkempt canyon

I must be an idiot I don’t understand how to implement it. It keeps saying that discord doesn’t have ext.

fading marlin
#

show code

sick birch
stable path
median flint
#

How do I mention a role?

rare echo
#

with the id? or?

median flint
#

I have a command that uses a role as one of its parameters, pyasync def tag(ctx, amount, role:discord.Role, *, message = ""):

#

and I can't figure out how to mention the role

median flint
rare echo
#

role.mention?

median flint
#

tried that

#

it just didn't work, no error, no nothing

rare echo
#

where did you put it?

median flint
#
@client.command()
async def tag(ctx, amount, role:discord.Role, *, message = ""):
  if await check_lock():
    return False
  try:
    amount = int(amount)
  except ValueError:
    await ctx.send("<amount> Must be a full number", delete_after=15)
  for i in range(amount):
    await ctx.send(f"{role}{message}")```
#

I also tried using an f""

#

but that didnt work

rare echo
#

why are you using .format like that?

median flint
#

I was just trying something else

rare echo
#

you can just
await ctx.send(f”{role.mention} {message}”)

#

my b on mobile can’t really format properly

median flint
#

np

#

I'll try again but it didn't seem to work the first time

rare echo
#

i think there’s a different issue then, mind taking a screenshot so i can see the layout?

median flint
rare echo
#

for your try and except you can just take in amount as an int

#

amount : int

#

as for the mention unless you already tried {role.mention} i’m not exactly sure what the issue is

median flint
#

Yeah I have tried the role.mention

#

i have no clue whats wrong with it

#

anyways thanks man

rare echo
#

what is check_lock?

#

or what relevance does that have

sick birch
#

Also you can typehint amount: int as an int

rare echo
slate swan
#

What is the event for when a bot comes online?

#

on_ready?

rich oxide
#

im having issue on makin a dsc bot bot and i cnt identity the error all it says is Traceback (most recent call last):
File "main.py", line 74, in <module>
bot.run("TOKEN") and sum html and css

#

but thrs nothing wrong in code

stable path
rich oxide
rich oxide
rich oxide
warm lava
torn sail
# rich oxide yes

It means u got ratelimtied, not ur fault tho. Side affect of replit

rich oxide
#

ok ill kill 1

warm lava
#

that happens to me in replit too

slate swan
#

im pretty sure

rich oxide
#

i alr did

slate swan
#

show full traceback

#

what you showed doesn't actually provide an error

rich oxide
#

hold on

#

okay im gettin new error here

warm lava
#

lemme see

unkempt canyonBOT
#

Hey @rich oxide!

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

warm lava
#

lol

rich oxide
#

Omg ill send in yalls dms

maiden fable
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.

rich oxide
#

I fixed @maiden fable

supple ridge
#

@maiden fable oi mate, is there any way to obfuscate code without pyarmor? like any alternative?

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1665378965:f> (10 minutes) (reason: mentions rule: sent 8 mentions in 10s).

The <@&831776746206265384> have been alerted for review.

supple ridge
supple ridge
maiden fable
slate swan
#

why obfuscate a discord bot tho just curious

supple ridge
slate swan
dusky kraken
#

!unittest

kind trellis
#

How can I make an argument be a true or false statement? For a slash command

wraith pendant
#
@client.event
async def on_ready():
    print("Bot is up.")

I used to run this at the beginning of my bot to notify me when the bot is up. I don't know what changed, but it doesn't work anymore.

#

It doesn't raise an error, it just doesn't work.

wraith pendant
#

yes

kind trellis
#

The token area got changed. It uses asyncio.run() now

meager chasm
rich oxide
#

Bot your less likely

meager chasm
#

No lol

#

Who told you that

rich oxide
#

happens to me

#

i figured myself

#

btw i wanna add econmy cmmds but idk how

meager chasm
#

discord.Client and commands.Bot are the same, just that commands.Bot has support for making commands easily

meager chasm
kind trellis
#

Under the migration section

slate swan
#

can someone explain how cooldown in hybrid commands work or refer me to their docs

slate swan
slate swan
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

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

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

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

A command can only have a single cooldown.
tough lance
#

Is there an alternative of Bot.get_context for inter class? (disnake)

slate swan
#

don't think so, you get context from message class, but interaction is a discord class in itself

slate swan
slate swan
#

make an error handler

#

if i add a interaction argument it just says this

#

wait give me 1 minute

#

The application did not respond

#
@whitelist.error
    async def on_whitelist_error(self, interaction:discord.Interaction, error):
        if isinstance(interaction,error,commands.CommandOnCooldown):
            await interaction.response.send_message(f"Command is on cooldown, you can use it after {round(error.retry_after, 2)} seconds.",ephemeral=True)
            ``` something like this? @slate swan
#

why would it be an interaction in a hybrid command

#

you get context for hybrid commands

#

but it will throw applicaiton not responding if i throw Context as an argument

#

@slate swan

#

no it wont. use ctx.send to create a response inside the error event

#

wait then

#
@whitelist.error
    async def on_whitelist_error(self, ctx:Context, error):
        if isinstance(ctx,error,commands.CommandOnCooldown):
            await ctx.send(f"Command is on cooldown, you can use it after {round(error.retry_after, 2)} seconds.")
            
#

your isinstance statement is faulty

#

what should it be then?

#

if isinstance(error, commands.CommandOnCooldown) ...

#

wait

#

it works now thanks man!

rich oxide
meager chasm
rich oxide
#

thx.

stable path
#

How would I get this to store what the user said?

#

Because I plan on storing the trigger and using regex to isolate the number after the +.

#

Then incorporate it into the final calculation to return the number with the modifier applied.

vocal snow
#

what do you mean "store what the user said?"

stable path
#

So I can put what they said into a variable.

vocal snow
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
vocal snow
#

I'm assuming you're looking for this

stable path
#

Cause rn the biggest issue is the variable modifiers.

slate swan
#

anyone know how i can have on_message and commands work at the same time

manic kernel
#

course you can, you just need to add a single line at the end of the on_message to process it as a command
await bot.process_commands(message)

or alternatively use a listener

warm lava
#

I need help

#

what is the importance of cogs?

manic kernel
#

allows you to easily partition your bot into multiple parts and load/unload them as required
also helps you NOT have a 50k line file as your bot grows and new features are introduced

#

the so called "modularity" of discord bots

upbeat gust
#

also groups into categories which can be seen from the help cmd

slate swan
#

bot wont even recognized this and... no errors nothing

#

is there something wrong

upbeat gust
slate swan
#

yeah

upbeat gust
#

Do you have the members intent

upbeat gust
slate swan
upbeat gust
slate swan
#

i load everything

upbeat gust
#

Show intents

slate swan
upbeat gust
#

you only have default + presences

slate swan
#

doesn't members come in default

upbeat gust
#

No

naive briar
#

No

#

It's an privileged intent

slate swan
#

ok

#

let me try again

upbeat gust
#

str(member) returns the full username + discrim though fyi

slate swan
#

and it works

slate swan
north escarp
#

!custom-check

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

north escarp
#

how can I add an error message here ?

def in_any_channel(*channels):
        async def predicate(ctx: Context):
            return ctx.channel.id in channels
        return check(predicate)```
still elbow
north escarp
still elbow
north escarp
still elbow
#

Error there

slate swan
#

Do people learn coding discord bots just as a hobby?

north escarp
#

@still elbow thanks for the help

rare echo
patent wagon
#

If someone steals my bots token can they : a)harm my account (log into my account b)log into discord developer portal

paper sluice
#

If someone gets your bot token, they can control your bot. You can regenerate your bot token in the dev portal if it has been leaked.

pastel basin
#
  file = File(fp=background.image_bytes, filename="wlcbg.jpg")

  welcome_embed = discord.Embed(description=f"Hii {member.mention}! Welcome To **{member.guild.name}**")
  welcome_embed.set_image(url="attachment://wlcbg.jpg")```
#

how can i set local image in my embed?

#

right now i can only see the description of embed

#

and i get no error and the image doesnt show up

honest shoal
#

and make sure you are providing the correct path

sick birch
#

Building it from ground up with JSON was probably not a good idea then, eh?

#

It's just None, not None()

primal token
#

None, True and False are all singleton unpolymorphic instances that cant be called!

slate swan
#

is it possible to run multiple bots with the same project ?.

slate swan
#

can you learn me how to do it ?

sick birch
vale wing
sick birch
#

Run them as seperate processes in different project directories

#

Much easier than trying to fiddle around with threading or multiprocessing

slate swan
#

i know but my objectif is to run them in one project 🙂😃

sick birch
#

Right, but why?

vale wing
#

Objective doesn't come out of nowehere

slate swan
sick birch
vale wing
#

^

sick birch
#

It's not really easier to run, harder to create, and you won't have a single "activity"

vale wing
#

Activity is android term

sick birch
#

What would be easier to run is to have each of your bots in their own container, then run docker-compose up and start up all 3 bots at once

slate swan
sick birch
slate swan
#

but i want to learn it 😃

vale wing
#

Learn docker?

sick birch
#

Docker is probably better to learn than threading IMO

#

One of the most widely used DevOps tools

slate swan
#

._.*

vale wing
#

Threading is important too ofc but not for this case

sick birch
#

I can see why you want to learn it, threading and multiprocessing are both important, but they're not always used, and only used in certain cases. This is not one of those cases, you don't need threading here. If you do want to learn about it, RealPython has a good article you can use to learn threading: https://realpython.com/intro-to-python-threading/

In this intermediate-level tutorial, you'll learn how to use threading in your Python programs. You'll see how to create threads, how to coordinate and synchronize them, and how to handle common problems that arise in threading.

honest laurel
sick birch
honest laurel
#

Run multiple processes yeah

sick birch
#

It's usually easier to learn something when applied to a project that could benifit from said concept

honest laurel
#

With one bot it's a bit more complicated and only needed if you're hitting cpu limit

sick birch
#

When you try to apply something to a project that does not benefit, it just makes it harder to learn

vale wing
#

Sadly my docker guide PR hasn't gotten merged yet

sick birch
#

Thanks for the reminder

vale wing
#

I can link a bit of outdated version tho it doesn't differ that much