#discord-bots

1 messages ยท Page 39 of 1

cerulean shale
#

even the other cog is giving the same error

#

pls help ;-;

pale turtle
#

Can u send the file where you load the cogs? The main file

cerulean shale
#

I am kinda new to cogs btw

pale turtle
#

Ok so the file name includes .py, and you can't do that

#

If the filr name is warn.py, you should load:
cogs.warn

pale turtle
#

So use string slicing for that

cerulean shale
#

Can you give an example pls ๐Ÿฅฒ

#

Like the complete part, cogs=[names] then the load.extension

#

I seriously don't know where to place that load.extension thing ๐Ÿฅฒ

pale turtle
cerulean shale
#

Like? ๐Ÿ˜ญ

pale turtle
#

!e
file_name = "warn.py"
print(file_name[:-3])

unkempt canyonBOT
#

@pale turtle :white_check_mark: Your 3.11 eval job has completed with return code 0.

warn
atomic parcel
#

does anyone know how i can make a discord bot that pings people in my server every time my roblox game is updated

cerulean shale
cerulean shale
pale turtle
#

No why

cerulean shale
#

Oh wait nvm

pale turtle
#

Look you get from the directory file names warn.py, and you want to remove the .py part of it, last three chars

cerulean shale
#

Ight got you

ionic edge
#

none of the commands are working now

#

after the upgrade

rancid stump
#

yo guys

slate swan
rancid stump
#

how to add multiple client.event in bot ?
i have written a python discord but the thing is it got alot of if condition so i want to deconstruct into small functions

slate swan
#

Why not use .listen() instead.

rancid stump
#

im using this method which is fucking shit

rancid stump
slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
cerulean shale
#

@pale turtle thx alot bro, it works now

rancid stump
#

i just have to replace client.event with client.listen() right ?

slate swan
#

you can do

@client.listen('on_message')
async def some_listener(ctx) -> None:
     # do something
glad cradle
ionic edge
#

๐Ÿฅฒ

rancid stump
slate swan
ionic edge
slate swan
#

๐Ÿ˜ญ

#

Just fix it

rancid stump
#

@slate swan ?

ionic edge
#

๐Ÿ˜ข

slate swan
rancid stump
slate swan
#

do you not define client anywhere?

glad cradle
#

@ionic edge in d.py 2.0 the setup functions of cogs are coroutines that means that you need to do async def setup(...) and await bot..... there are other breaking changes, check the docs

cold sonnet
#

self-explanatory

rancid stump
slate swan
#

client = commands.Bot(..)

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
pale turtle
slate swan
limber bison
#

I use asyncio.sleep() , how can I stop it with other commands ?

cold sonnet
#

no wa

silk fulcrum
#

use schedules

#

instead of sleep

cold sonnet
#

or use a botvar

#

but the command will only work one at a time

#
await asyncio.sleep(time)
if botvar_for_check == True:
    do shit
#

don't recommend

silk fulcrum
#

schedules are gud

ionic edge
#

how can i use slash command and prefix command together??

ionic edge
glad cradle
silk fulcrum
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.
cold tide
#

I need a bot that deletes channels since my server just got nuked.

#

๐Ÿ˜ญ

pale turtle
#

Delete channels? Y would u want that

cold sonnet
#

because someone made many channels on his server

#

those people you don't wanna give admin to

ionic edge
ionic edge
#

@cold tide

#

but do it fast

glad cradle
#

๐Ÿ˜

ionic edge
sour basalt
#

message = await ctx.reply(file = discord.File(spin['path'])) how i can i add this on embed?

cold tide
#
await channel.delete()```
#

its not deleting why?

vocal snow
#

are you getting an error?

#

If not, do you have an error handler?

#

Are you sure your bot has the required permissions? Is channel a valid object with a delete method?

ionic edge
slate swan
#

๐Ÿ‘๏ธ ๐Ÿ‘๏ธ

slate swan
slate swan
slate swan
#

its an example mrpithink

#

Ik I was just saying along with what his code says

#

and you can always say while True over while 1 since a number thats not 0, boolean value is True

slate swan
slate swan
silk fulcrum
#

r i p

slate swan
#
while 9000-8999:
    print('a')

๐Ÿ˜ญ

silk fulcrum
#

also @slate swan my cat is here, with me, safe, without being kidnapped

slate swan
#

not for long

silk fulcrum
#

prove

slate swan
silk fulcrum
silk fulcrum
#

๐Ÿ˜ณ

slate swan
#
while 10/2*2-2.4:
    print('a')
#

while float("NaN"): print("a") ๐Ÿ˜ณ

#

??

#

!e while float("NaN"): print("a")

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | a
002 | a
003 | a
004 | a
005 | a
006 | a
007 | a
008 | a
009 | a
010 | a
011 | a
... (truncated - too many lines)

Full output: too long to upload

slate swan
#

NaN is true or what

silk fulcrum
#

while True: print('a') ๐Ÿคฆโ€โ™‚๏ธ

slate swan
pliant gulch
#
[print("a")for _ in iter(int,1)]
slate swan
#

0, [], (), "", {}, etc are falsey

slate swan
#

๐Ÿ’€

slate swan
silk fulcrum
slate swan
silk fulcrum
#

otherwise how is he inside my walls and kidnapping my cat without kidnapping it

slate swan
slate swan
slate swan
#

its CoS

#
def cute(sarth: Sarth) -> CuteAndSarth[OkimiisLove]:
    ...
silk fulcrum
#

no its VCaSaO (Very Cute and Smart and Okimii)

slate swan
#

im not smart, im smortyert

silk fulcrum
#

you are smart

slate swan
pliant gulch
#

Just need to add function decl & function calling and I'll be able to use discord.py in my programming lang

silk fulcrum
#

lol whatt

slate swan
sour basalt
#

await bot.sleep(300)
AttributeError: 'Bot' object has no attribute 'sleep'

pliant gulch
# slate swan is it like python compatible?

Yes it's python interoperable , meaning you can use ANYTHING from python inside of my programming language (if I have actually added the ast) and it also means you can import my programming language into python

slate swan
#

andy is the type of person to bully someone for using rust and continue using ruby

silk fulcrum
pliant gulch
#

The programming language compiles to python bytecode

slate swan
#

wtf

slate swan
pliant gulch
silk fulcrum
slate swan
pliant gulch
#

Python and it compiles to python bytecode

slate swan
slate swan
pliant gulch
#

Later I'll bootstrap the compiler

#

Meaning soon the programming lang will be written in itself

silk fulcrum
#

wait did you guys really not get that was a joke?

#

@slate swan is bot an instance of asyncio?

heavy swift
slate swan
#

what

#

i mean you can actually use discord.utils.Union instead of typing.Union so there's no jokes in this channel

pliant gulch
slate swan
heavy swift
#

Bootstrap is a css framework, how are you going to "bootstrap" the compiler

silk fulcrum
#

there's not only that bootstrap

pliant gulch
slate swan
pliant gulch
#

Bootstrapping in the compiler context means writing the compiler in the language your compiler compiles

slate swan
#

basically built in itself

pliant gulch
#

Yes hence bootstrap

heavy swift
#

I see lemon_thinking

slate swan
# heavy swift Bootstrap is a css framework, how are you going to "bootstrap" the compiler

In computer science, bootstrapping is the technique for producing a self-compiling compiler โ€“ that is, a compiler (or assembler) written in the source programming language that it intends to compile. An initial core version of the compiler (the bootstrap compiler) is generated in a different language (which could be assembly language); successiv...

#

iirc python has a bootstrapped version named pypy

silk fulcrum
#

btw what description do I put for a ping command?

heavy swift
#

So I should assume the same wouldn't apply to tailwind lol "I'm going to tailwind my compiler"

slate swan
#

Bot latency mb

silk fulcrum
#

oh wait im smart, ill put "Pong!"

slate swan
#

every bot does that

silk fulcrum
#

what? really?

heavy swift
#

That's why I put bong for mine

slate swan
#

ping is actually the heartbeat latency in respect to the websocket, nothing to do with speed

#

Oh

silk fulcrum
#

well, not exactly "Pong!"

#

so im new

slate swan
heavy swift
#

It's more of a convention like "Hello world"

slate swan
#

its called ping and pong because of ping and pong frames

pliant gulch
#

Wouldn't it have something at least to do with speed?

heavy swift
#

not necessary

slate swan
#

it depends on your internet connection ofc, but there much more factors ( like the server side connection etc)

pliant gulch
#

It is the speed at which a packet was sent between you and the service

silk fulcrum
slate swan
bleak atlas
#

Hi, I would like to create a help command (I'm using slash commands) but I don't see anything in the docs, I'm looking for something like the default help command with normal commands, is that possible with slash commands or do I have to create it manually? Thanks.

silk fulcrum
pliant gulch
silk fulcrum
#

everything is built-in

#

arguments, options, description

heavy swift
slate swan
silk fulcrum
slate swan
slate swan
vocal snow
#

rich western country moment

slate swan
#

cries in 50mbs

silk fulcrum
#

me at my 69 download speed

pliant gulch
slate swan
#

it's not that bad though, like 100 a month

vocal snow
#

100 what

slate swan
#

Moneys

vocal snow
#

what currency

slate swan
#

USD

#

๐Ÿ—ฟ what currency

heavy swift
#

that's a lot

slate swan
#

fiber internet travels through glass

#

i pay like 250โ‚น for 3 gbs daily

silk fulcrum
#

almost got the 69

vocal snow
#

rich western country thinking 100USD a month isn't a lot of money ๐Ÿ’€

junior verge
#

How do you do this again Im stupid I forgot, how do I enter an channel and with get channel, and then just send channel.send etc

slate swan
#

was it lightwaves or something like that i forgot the correct term

vocal snow
#

genius

silk fulcrum
#

at least for me

#

at least for russia

slate swan
slate swan
heavy swift
#

There's a lot of places where u cant just "move"

slate swan
#

yes you can

#

get plane, fly plane, land plane

#

walk from your room to your kitchen

heavy swift
#

No because your wealth determines that

heavy swift
slate swan
#

no need for wealth when you can just move from your room to your kitchen๐Ÿ˜ณ

#

๐Ÿคฏ

slate swan
#

oh my

bleak atlas
junior verge
slate swan
#

what provider is that

silk fulcrum
#

not your wifi moment

slate swan
#

๐Ÿ˜ณ

slate swan
silk fulcrum
#

@slate swan i wanna sleep, but i dont wanna sleep cus this is the only time you are online

slate swan
junior verge
slate swan
#

!d discord.utils.get

unkempt canyonBOT
#

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

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

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

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

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
fresh orchid
slate swan
bleak atlas
slate swan
#

bro is using his microwave as his router

fresh orchid
#

Lmao

#

It will be better soon

slate swan
silk fulcrum
fresh orchid
slate swan
#

what

#

oh okay

#

good thing i dont live in EU

#

decimal points more like decimal comas lemon_imp

fresh orchid
#

, are cooler

full lily
slate swan
#

no

junior verge
slate swan
junior verge
fresh orchid
slate swan
slate swan
slate swan
silk fulcrum
#

me in russia: 12 345 678

slate swan
#

ETF

slate swan
fresh orchid
#

12.345.678

slate swan
fresh orchid
#

Or just ignore the dots and do 12345678

But it looks better with .

slate swan
#

indeed

junior verge
slate swan
#

you should use or if the method returns None

junior verge
#

I just forgot how it works ๐Ÿ˜ซ

#

nvm I got it lol

#

I should sleep lol

slate swan
#

bot.http.send_message()

slate swan
#

internal methods๐Ÿ˜ญ

#

it gets involved in the end anyways

#

yup

drifting arrow
#

Hey, I am working with the new slash commands, and I want to know if interactions act the same as ctx? Where I can check the channel and what not

#

so I can limit an interaction (slash command) to specific channels.

junior verge
#

What does a client.event need to be in a cog?

vocal snow
#

commands.Cog.listener

junior verge
#

ah yeah lol ty

#

oh self, guild?

#

ah yeah nvm

viral wolf
#
@bot.slash_command(description="Repeats you, use /say (what you want to say)")
async def say(inter, what_to_say):
    await inter.channel.send(what_to_say)
    #finish interaction

What command would i use instead of finish interaction?

sour basalt
#

bot = commands.Bot(command_prefix=!,activity=activity,status=discord.Status.idle,intents=discord.Intents.default(),)
^
SyntaxError: invalid syntax

slate swan
#

remove the last comma

hazy oxide
#

Your command prefix should be string

sour basalt
#

ok

slate swan
#

yeah that too lol

sour basalt
#

,

viral wolf
slate swan
hazy oxide
#

Oh, ephemeral

sour basalt
#

bot = commands.Bot(command_prefix='!',activity=activity,status=discord.Status.idle,intents=discord.Intents.default()) my bot nont respond at !

viral wolf
hazy oxide
slate swan
viral wolf
#

Alright ill look into that

junior verge
#
@commands.Cog.listener()
    async def on_guild_join(self, guild):
        try:
            link = await random.choice(guild.text_channels).create_invite()
        except:
            link = "I don't have perms to create an invite"
            channel = await self.client.fetch_channel(1009210344020905994)
            embed = discord.Embed(title=f"Added to server", color=0x00ff00)
            embed.add_field(name=f"Server Name:", value=guild.name, inline=False)
            embed.add_field(name=f"Server ID:", value=guild.id, inline=False)
            embed.add_field(name=f"Owner Name:", value="f{guild.owner}", inline=False)
            embed.add_field(name=f"Owner ID:", value=guild.owner_id, inline=False)
            embed.add_field(name=f"Membercount:", value=f"{{len(guild.members)}}", inline=False)
            embed.add_field(name=f"Invite:", value=f"{link}", inline=False)
            await channel.send(embed=embed)
``` Why doesn't this work? Doesn't error either
slate swan
#

wdym by doesnt work?

#

does it get triggered? you should use print to debug it

junior verge
#

Just doesn't send the message where it should

junior verge
viral wolf
#

What I mean is i dont want the Twilight used /say to be there, But I want the response to be visible to anyone, so whoever sent the message is anonymous

vocal snow
junior verge
mossy jacinth
vocal snow
junior verge
vocal snow
#

you aren't sending anything if the invite link is created succesfully

#

you're only sending if there was an exception raised when creating it

junior verge
#

oh

#

ill remove the try and except

viral wolf
slate swan
slate swan
#

just use Interaction.send and send one message thats ephemeral and that other one thats not ephemeral internally disnake would check if the interaction was already responded to and sends a message with a newly created webhook

slate swan
sour basalt
slate swan
#

do you have 2 on_messages?

#

if so, you should use listen

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
sour basalt
slate swan
#

can you show your code?

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

sour basalt
#

from discord.ext import commands
import discord
import asyncio
import random
import os

activity = discord.Activity(type=discord.ActivityType.watching, name="Tsw X IlTelegatto")
bot = commands.Bot(
command_prefix=commands.when_mentioned_or('!'),
activity=activity,
status=discord.Status.idle,
intents=discord.Intents.default(),
)

slate swan
#

thats all your code?

sour basalt
slate swan
#

and why the trailing comma?

sour basalt
#

what is trailing

mossy jacinth
gusty shard
#
@bot.command()
@commands.has_permissions(manage_messages=True)
async def delete(message, limit: int):
        await message.channel.purge(limit=limit + 1)
        await message.send(f'{limit} message deleted by {message.author.name}.', delete_after=2)```
how can i make bot reply to users who dont have permission to manage_messages?
pale turtle
#

Using error handler I think

gusty shard
#

lets try

slate swan
#

how to make <@userid> into user id

#

i tried int()

#

but got ValueError: invalid literal for int() with base 10: ''

gusty shard
# pale turtle Using error handler I think
@bot.command()
@commands.has_permissions(manage_messages=True)
async def delete(message, limit: int):
        await message.channel.purge(limit=limit + 1)
        await message.send(f'{limit} message deleted by {message.author.name}.', delete_after=2)
@delete.error
async def delete_error(ctx, error):
    if isinstance(error, PermissionError):
        await ctx.reply('You dont have permission to do this.', delete_after=2)```
#

it didnt worked

pale turtle
#

Isn't it MissingPermissions or something?

gusty shard
#

i tried that too

#

it looks like that, i dont know what to do

pale turtle
#

Try to raise the error and see what it says

gusty shard
#
discord.ext.commands.errors.MissingPermissions: You are missing Manage Messages permission(s) to run this command.```
#

should i make it error.MissingPermissions?

pale turtle
#

Did you try to import the error?

gusty shard
#

what do you mean

#

i dont knwo much about the error handling but

pale turtle
#

I mean try to do: commands.MissingPermissions

raw cairn
gusty shard
#

is it a module?

#

oh

slate swan
#

its a class

gusty shard
#

should i always use commands or is it just for some cases?

slate swan
#

hence the UpperWord naming

mossy jacinth
heavy swift
gusty shard
slate swan
sick birch
heavy swift
sick birch
slate swan
raw cairn
gusty shard
#

thank you

raw cairn
#

np

heavy swift
mossy jacinth
heavy swift
slate swan
coral flame
#

i'm trying to define some application commands inside of my commands.Bot subclass, yet am running into an issue. If i don't call tree.add_command for the commands and go to run the commands, I get CommandNotFound, yet when I add it and then sync, I get CommandSignatureMismatch. What exactly am i doing wrong?

raw cairn
#

DO you have another variable or function called uptime?

slate swan
sick birch
heavy swift
coral flame
#

wdym comment out the handlers? you mean the commands themselves?

#

i'll try that

mossy jacinth
slate swan
#
            usern = bot.fetch_user(int(msg.content))```
slate swan
#

LMAO

#

bros in the future

heavy swift
slate swan
#

ur too powerful

deep osprey
#

discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward. why am I getting that error?

deep osprey
slate swan
deep osprey
#

what to use?

slate swan
#

pc

heavy swift
#

You need a check function because your msg var isn't actually the message being sent, it's waiting for your button to be pressed

deep osprey
#

yes I am

sick birch
#

That explains it

slate swan
heavy swift
deep osprey
#

is replit that bad?

sick birch
leaden jasper
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**...
heavy swift
#

yes

slate swan
leaden jasper
#

it's not required too

slate swan
deep osprey
#

are there any other free hosting services?

leaden jasper
#

@sick birch where to write server questions?

dire pier
#

why doesnt my blacklist system work?

client.blacklisted_users = []
def read_json(filename):
    with open(f"blacklist.json", "r") as file:
        data = json.load(file)
    return data

def write_json(data, filename):
    with open(f"blacklist.json", "w") as file:
        json.dump(data, file, indent=4)

#Cog...

  @commands.Cog.listener()
  async def on_message(self, message):
    if message.author.id in client.blacklisted_users:
      return




  @commands.command()
  @commands.check(jet)
  async def blacklist(self, ctx, user: Union[discord.Member, discord.User] = None):
    if ctx.author.id == user.id:
        await ctx.send("Hey, you cannot blacklist yourself!")
        return

    client.blacklisted_users.append(user.id)
    data = read_json("blacklist")
    data["blacklistedUsers"].append(user.id)
    write_json(data, "blacklist")
    await ctx.send(f"Hey, I have blacklisted {user.name} for you.")

  @commands.command()
  @commands.check(jet)
  async def unblacklist(self, ctx, user: Union[discord.Member, discord.User]):
    client.blacklisted_users.remove(user.id)
    data = read_json("blacklist")
    data["blacklistedUsers"].remove(user.id)
    write_json(data, "blacklist")
    await ctx.send(f"Hey, I have unblacklisted {user.name} for you.")

{
    "blacklistedUsers": [
        numbers,
    ]
}
  async def on_ready(self):
    print('{0.user}'.format(self))
    print('Is Online')
    print('-----------')
    print(discord.__version__)
    data = read_json("blacklist")
    client.blacklisted_users = data["blacklistedUsers"]
#

no errors

slate swan
#

or else buy cheap vps

slate swan
dire pier
deep osprey
slate swan
slate swan
deep osprey
gusty shard
#

how to check if somebody adds a role to somebody else?

fading marlin
#

or on_member_update

#

pretty sure it's for the on_typing event

limber bison
#

ctx.guild.default_role in ctx.author,roles // is this always true ?

whole sparrow
#

How often can you change a channel name with a discord bot? Whats the ratelimit

whole sparrow
#

Tysm

#

How do you error handle "Application did not respond"

#

Is there a way?

pliant gulch
#

Make sure to actually respond to any interactions

#

E.g, sending a message with the Interaction, deferring the reaction, etc

#

All reactions in the discord API must have a resposne

whole sparrow
#

The issue I have is that im getting ratelimited by changing channel name too often

#

I want to send a message saying its been successful on one hand

#

but how do I error handle and state that It didnt work out after interaction fails@?

pliant gulch
#

Before you make the request to the API for changing the channel name do some checks before hand

#

You can, for an example set a dictionary with some context and a datetime object

gusty shard
#

is it possible to create a field without value?

pliant gulch
#

Pretty basic example, all your doing here is just checking whether or not you have waited long enough inbetween the calls

whole sparrow
#

Really helpful, thanks alot

#

also, why use := instead of ==?

#

Are they not the same? Im just curious

rugged shadow
gusty shard
#

the horses on this race are looking same

rugged shadow
gusty shard
#

its not possible without using emty fields

pliant gulch
#

!e ```py
wait = {"foo": "exists"}

if time := wait.get("foo"):
print(time)

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.

exists
gusty shard
rugged shadow
gusty shard
#

what are the horses

rugged shadow
#

the horses are just in the description

pliant gulch
gusty shard
whole sparrow
#

Oo thats handy, thanks alot

gusty shard
#

how can i make that without using \n's

rugged shadow
#

use multiline strings

gusty shard
#

oh my bad

#

sorry

rugged shadow
#

np

slate swan
#

Anyway to do like an user can click the button once, but when they click it again it would say โ€œyou canโ€™t click this button twiceโ€
I donโ€™t want to disable / stop the view after button click

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @noble walrus until <t:1660698389:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

gusty shard
#

i need help again

rugged shadow
#

sure?

gusty shard
#

i need to add some spaces between the horses

#

i tried putting \n's after every horse

#

but it didnt worked

slate swan
gusty shard
#
      • ๐Ÿ‡
        • ๐Ÿ‡

istead of

      • ๐Ÿ‡
        • ๐Ÿ‡
slate swan
#

ah

#

what's your code rn for the embed

gusty shard
#

its a little bit bad

#
embed2 = discord.Embed(title=f"{num}. tur.")

embed2.add_field(name=f" - " * atlar[0] + " :horse_racing:\n", value=f" - " * atlar[1] + " :horse_racing:\n", inline=False)

embed2.add_field(name=f" - " * atlar[2] + " :horse_racing:\n", value=f" - " * atlar[3] + " :horse_racing:\n", inline=False)

embed2.add_field(name=f" - " * atlar[4] + " :horse_racing:\n", value="hbc#1111", inline=False)```
#

i'll fix it when i complete the command

slate swan
#

interesting concatenation

slate swan
gusty shard
#

yes

slate swan
#

why not make a blank field in between each line thingy

embed2.add_field(name = chr(173), value = chr(173))
gusty shard
#

what do you mean

slate swan
#

example

embed2 = discord.Embed(title="..")
embed2.add_field(one horse)
embed2.add_field(name = chr(173), value = chr(173)) # blank line
embed2.add_field(another horse)
#

and it should go like

      • ๐Ÿ‡
        • ๐Ÿ‡
#

@gusty shard did you try it?

gusty shard
#

whats that?

slate swan
#

it's an empty character

#

just gets the unicode character for 173

gusty shard
#

ohh

slate swan
#

try it out, let me know if it works. It should

gusty shard
#

theres one problem

#

i have two horse per field

#

how can i put one horse to one field

slate swan
#

just split them up into all seperate fields?

gusty shard
#

isnt it impossible to create a field without value

#

actually i can put chr(173) to the values

#

let me try

slate swan
#

try

#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
gusty shard
#

that works perfectly

#

thank you y9

#

you are legend

cerulean shale
#

Yo, after this month, all the bots should migrate to slash comands right, what will happen if we don't?

slate swan
#

wasnt that delayed to 2023 or something

maiden fable
slate swan
#

mhm

maiden fable
#

The deadline is August end

slate swan
#

mhm cool

#

I need help

#
Embed = Discord.Embed(
            title = 'Snake game',
            description = '''
            :blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square::blue_square: \n
            :bue_square::purple_square:
            ''',
            color = 0x00FF80);
#

i'm trying to make an embed and right now im trying to make a grid

#

it would look like this

fluid shadow
unkempt canyonBOT
#

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

wary shadow
#

!unmute 769441935654912000

unkempt canyonBOT
#

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

slate swan
#

Thank you

#

I didn't know about the emoji ban, crikey.

wary shadow
#

Can't post that many emotes. ;) If you want to share images of what it looks like I'd suggest a help room.

slate swan
#

Okay

#

thank you

#

Like that ^^^ but scaled bigger

#

20x20

#

but im not sure how to do that...

#

actually wait I might have an idea

#
Length = 20;
    def __init__(self, Message):
        self.Message = Message;
    
    async def Activate(self):
        Description = ':blue_square:' * self.Length + '\n'
        for i in range(1, 19):
            Description = Description + ':blue_square:' + (":purple_square:" * 18) + ":blue_square:" + "\n"
        Description = ':blue_square:' * self.Length
        print(Description)

Why isn't this working? it just shows 20 blue squares

#

nvm figured it out

#

Can someone help me make snake for a discord bot

#

I'm a little confused.

limber bison
#

Uid , roleid and any other I'd comes in int or long int (MySQL) ?

slate swan
#

BIGINT

slate swan
#
async def Activate(self):
        Description = ':blue_square:' * self.Length + '\n'
        for i in range(1, 5):
            Description = Description + ':blue_square:' + (":black_large_square:" * 9) + ":blue_square:" + "\n"
        Description = Description + (':blue_square:') + (':black_large_square:' * 4) + ':flushed:' + (':black_large_square:' * 4) + ":blue_square:" + '\n'
        for i in range(1, 5):
            Description = Description + ':blue_square:' + (":black_large_square:" * 9) + ":blue_square:" + "\n"
        Description = Description + ':blue_square:' * self.Length
``` I have this code to make a snake grid.
#

I think I am doing it wrong though, shouldn't have I have coordinate points for the grid?

#

I think I am going about it the wrong way

slate swan
slate swan
#

:p

slate swan
#

the kids in my basement

slate swan
#

i live with @maiden fable

slate swan
#

Okay wait is this a good plan?

#

I'll make a dictionary of vector3s

#

and then...

#

nevermind im so confuse

vale wing
# slate swan

If you are making it with emojis you better don't, cause on some devices the thing's gonna get messed up

#

Use pillow and render images

vale wing
slate swan
#

vector2

vale wing
#

Yeah

slate swan
#

mb

#

i just dunno

vale wing
#

And what for would you need a dictionary

slate swan
#

for the coordinates

#

I mean im doing it as a discord bot

vale wing
#

Like there's only x y for the snake

slate swan
#

idk i just need help ๐Ÿ˜ญ

vale wing
#

Does it get longer or smth

#

Try to make that game in terminal first

#

To create a principle and then transfer it to the bot

#

Not to have delays with testing

slate swan
#

yes

#

Okay

#

@vale wing I mean I only know ho wto use pygame

#

im sorry im so new to thsi

vale wing
#

Also pygame has nothing to do with a discord bot

slate swan
#

but how do I make a game in the terminal?

vale wing
#

If you will be using image generation it doesn't really matter where you do it

#

If not just use like # for walls and ! for the snake or smth

#

And create that thing as text

#

You can even use your emojis if terminal is ok with displaying them

slate swan
#

Okay wait Exenifix

#

please explain im sorry

#

How do I even use the terminal

vale wing
#

Console

#

What I mean is your code's output will be in your console not in discord bot

slate swan
#

Okay

deep osprey
#
@bot.command()
@commands.is_owner()
async def view(ctx, arg) -> None:
    async with aiofiles.open(f'{arg}.txt', mode='r') as f:
        try:
            lines = await f.readlines()
            x = len(lines)
            z = len(await f.read())
            if z > 2000:
                  await ctx.send(file=f'{arg}.txt')   
            else:
                await ctx.reply(''.join(lines))
                await ctx.send(f"Total lines: {x}")
        except Exception as e:
            raise e``` why doesn't it send the file?
slate swan
vale wing
#

Nah pure python

#

For images generation you would have to use pillow tho as I said

slate swan
#

oh okay

limber bison
#

Where I can get free hosted mySQL

shrewd apex
silk fulcrum
#

any way to disable some slash commands on a specific server with leaving them global? or the only way is specifying on which guilds they will work?

slate swan
silk fulcrum
#

and i want to completely disable command on a server, however this is also helpful, except I'd want this as a decorator

torn sail
unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
torn sail
#

No way to not make the command show up unless u sync per guild which is bad

slate swan
#

you can't completely hide a specific global command

silk fulcrum
#

and will do

slate swan
#

yeah an ephemeral response sounds just right for the purpose

slate swan
#
{
  "response": {
    "players": [
      {
        "steamid": "76561199084247549",
        "communityvisibilitystate": 3,
        "profilestate": 1,
        "personaname": "Aethra",
        "commentpermission": 1,
        "profileurl": "https://steamcommunity.com/profiles/76561199084247549/",
        "avatar": "https://avatars.akamai.steamstatic.com/988a9289a0c11c184cfd1eec707e4719a00ff993.jpg",
        "avatarmedium": "https://avatars.akamai.steamstatic.com/988a9289a0c11c184cfd1eec707e4719a00ff993_medium.jpg",
        "avatarfull": "https://avatars.akamai.steamstatic.com/988a9289a0c11c184cfd1eec707e4719a00ff993_full.jpg",
        "avatarhash": "988a9289a0c11c184cfd1eec707e4719a00ff993",
        "lastlogoff": 1660613718,
        "personastate": 1,
        "realname": "Aethra",
        "primaryclanid": "103582791429521408",
        "timecreated": 1597861298,
        "personastateflags": 0,
        "loccountrycode": "CA",
        "locstatecode": "ON"
      }
    ]
  }
}
#

The json information when I call it isn't sending

primal token
#

you really shouldnt be creating a connection uppon each call

slate swan
#

Sorry?

primal token
#

you shouldnt be creating a session in aiohttp uppon each call of the command.

silk fulcrum
#

what have I done wrong?

slate swan
#

Oh, alright.

#

But that currently isn't the issue

primal token
#

whats the issue, it doesnt send the value parsed?

slate swan
#

Correct

#

I sent the json file the api provides

#

When I call the information it doesn't send anything.

primal token
#

have you loaded the cog and are you sure your command is being triggered?

slate swan
#

Yes

#

I'm affirmative

#

When I call "Response" it calls all the information

#

But when I parse anything else in the file it shows nothing

#

or call the value parsed

slate swan
silk fulcrum
primal token
slate swan
silk fulcrum
#

that commands show up

#

for a user that doesnt have any perms

slate swan
#

check in server integrations that the command perms got updated or not

#

The cog is loaded to main. if I make it send content['responses'] it sends

"players": [
      {
        "steamid": "76561199084247549",
        "communityvisibilitystate": 3,
        "profilestate": 1,
        "personaname": "Aethra",
        "commentpermission": 1,
        "profileurl": "https://steamcommunity.com/profiles/76561199084247549/",
        "avatar": "https://avatars.akamai.steamstatic.com/988a9289a0c11c184cfd1eec707e4719a00ff993.jpg",
        "avatarmedium": "https://avatars.akamai.steamstatic.com/988a9289a0c11c184cfd1eec707e4719a00ff993_medium.jpg",
        "avatarfull": "https://avatars.akamai.steamstatic.com/988a9289a0c11c184cfd1eec707e4719a00ff993_full.jpg",
        "avatarhash": "988a9289a0c11c184cfd1eec707e4719a00ff993",
        "lastlogoff": 1660613718
        "personastate": 1,
        "realname": "Aethra",
        "primaryclanid": "103582791429521408",
        "timecreated": 1597861298,
        "personastateflags": 0,
        "loccountrycode": "CA",
        "locstatecode": "ON"
      }
    ]
  }
}
primal token
#

do you have error handlers?

slate swan
#

what part of the response do you want

#

No, I do not

#

I have command error event, that's all

primal token
#

wrong index

slate swan
#

sorry?

primal token
#

the parsing should be

content["players"][0]["steamid"]
slate swan
#

omg

#

What a silly mistake.

#

fuck, my bad.

primal token
#

programming is all about trial and error

#

mostly errors lol

slate swan
#

Well, honestly this is like my first time using json

#

And I don't often use dictionary

primal token
#

well i recommend you look up on it

#

parsing a hashmap is essential for dealing with APIs

slate swan
#

Hey, once it LOL

#

It's not quite working ๐Ÿ˜…

#

Like, nothing is sending once I execute the command

primal token
#

can you try to print something after sending a message?

slate swan
#

Come again?

#

Like once the ctx.send is complete print something?

primal token
#

that is correct

slate swan
#

Okay, nothing is sending after

#

printing

primal token
#

Do you mean nothing is printing?

slate swan
#

Correct

#

ONce the command is executed nothing is sending or printing

primal token
#

seems like the context manager exited

slate swan
#

So, what can I do about this?

silk fulcrum
slate swan
# silk fulcrum i guess so?

well its allowed for everyone according to the interface
and wait, you cant set permissions for a subcommand, permissions are limited to commands

#

subcommands are actually just command options

silk fulcrum
#

bruh

#

what do I do?

#

i have prefix show (fallback) that should be allowed to everyone

#

others for admins

slate swan
#

there's app commands checks that you can use for the add command

slate swan
#

a normal check like you used for your command earlier

#

you cant hide a subcommand

silk fulcrum
#

sadge:(

bleak atlas
#

Hi, I'm trying to make an embed creator using modals, but I need to get user input in how many fields they want in the embed, but I can't get the input from commands, because of how the code works, how can I get user input from this? Thanks.

class EmbedCreator(disnake.ui.Modal):
    def init(self):
        components = [
            disnake.ui.TextInput(
                label="Name",
                placeholder="Placeholder Name",
                custom_id="name",
                max_length=25,
            )
        ]
        super().init(title="Title of modal", components=components)

    async def callback(self, interaction) -> None:
        embed = disnake.Embed(title="Tag creation")
        for key, value in interaction.text_values.items():
            embed.add_field(name=key, value=value, inline=False)
        await interaction.response.send_message(embed=embed)


@client.slash_command()
@has_permissions(administrator=True)
async def send_modal(inter,
                     fields: int = commands.Param(name="fields",
                                                  description="The amount of fields you want in the embed.")):
    await inter.response.send_modal(modal=EmbedCreator())

junior verge
#

Is there a way for the bot to leave the server? Such is a like a command .leave serverid and it wil leave that?

cerulean shale
#

You can try this ig

#

Just define the guild and you will be fine

slate swan
#
async def register(ctx):
    with con:
        con = sqlite3.connect('userinfo.db')

        cur = con.cursor()
    
        cur.execute("""CREATE TABLE IF NOT EXISTS userinfo (
                    userid = ctx.message.author.id INTEGER
                    balance = 0 INTEGER""")```

im new to sqlite3,  i need help with my currency bot register command.
#

sorry if there are lots if mistakes in my code :/

junior verge
# cerulean shale await self.bot.leave_guild(guild)
@commands.command()
    async def test(self, ctx, guild):

        id1 = 813824599522541628
        id2 = 574217755692236803
        if ctx.message.author.id == id1 or ctx.message.author.id == id2:
            await self.client.leave_guild(guild)
#

Something like that?

junior verge
#

await what

cerulean shale
#

await self.client.leave_guild(guild)

junior verge
#

I have that?

dull terrace
#
with con:
    con = sqlite3.connect('userinfo.db')```

this part of your code doesn't make sense, you're saying with con but then defining con immediately after
slate swan
#

whats object_id? id? x? y? direction?
pls explain further

dull terrace
cold oyster
#

What's this?

dull terrace
#

those are my column names

slate swan
#

ah

cold oyster
dull terrace
cerulean shale
cold oyster
#
import disnake as discord
from disnake.ext import commands

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

@client.event
async def on_ready():
    print("Ready!")


@client.slash_command(name="ping")
async def ping(ctx):
    latency = round(client.latency * 1000)
    await ctx.send(f"Pong! The ping is `{latency}` ms", ephemeral=False)

@client.slash_command(name="echo", description="Send a message through the bot!")
async def echo(ctx,* ,text):
    await ctx.send("Your text has been sent.", ephemeral=True)
    await ctx.send(text, ephemeral=False)```
dull terrace
#

oh i think it's your ping slash command

#

it needs a description

cold oyster
#

Nope @dull terrace

dull terrace
# cold oyster oh

also use client = commands.InteractionBot() if you're using slash commands

cold oyster
#

mhm

dull terrace
#

that could be the other reason

cold oyster
#

leme try

dull terrace
#

i see nothing else there that could be a problem

cold oyster
#

No again

slate swan
#
async def register(ctx):
    with con:
        sqlite3.connect('userinfo.db')

        cur = con.cursor()
    
        cur.execute("""CREATE TABLE IF NOT EXISTS userinfo (
                    userid INTEGER,
                    balance INTEGER
                    """)```
#

is it correct now?

dull terrace
#

async def echo(ctx,* ,text): i don't get this line, what are you trying to do

cold oyster
dull terrace
#

7739monkathink you want the user to input something or?

junior verge
dull terrace
#

oh that's not how you do that

cold oyster
dull terrace
dull terrace
#

pretty sure that's how you'd do it

cold oyster
dull terrace
cold oyster
#

Dosent resolve the error still

dull terrace
junior verge
dull terrace
#

itll give you a list of all the possible attributes and you'll probably find one that makes sense for what you're trying to do

junior verge
#

Hm?

#

I just want it to leave a server when I do .leave serverid and it needs to leave that thats all

vale wing
#

The quicker is to check the docs for Guild object

#

!d discord.Guild check methods

unkempt canyonBOT
#

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

This is referred to as a โ€œserverโ€ in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guildโ€™s hash.

str(x) Returns the guildโ€™s name.
vale wing
#

Yeah use this lol

slate swan
junior verge
slate swan
#

fixed it

vale wing
#

Get guild object and use leave method

junior verge
#

just ```py
await self.client.leave(guild)

vale wing
#

Nah man

junior verge
#

oh

vale wing
#

You get guild object with bot.get_guild

junior verge
#

No but I will enter in the ID, you get me?

vale wing
#

Yes so what

#

Parse it to get_guild

junior verge
#

self.client.get_guild.leave idk

vale wing
#

Read about OOP when you have time

junior verge
#

I'm just trying to ask what it is lol

vale wing
#

Understand the principle of types, methods and objects

vale wing
#

As a qualified pedagogical worker I discourage such methods

dull terrace
#

pedagogical

slate swan
#
async def register(ctx):
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute("""CREATE TABLE IF NOT EXISTS userinfo (
                userid INTEGER,
                balance INTEGER
                """)

    INSERT INTO userinfo (userid, balance)
    VALUES:
        (ctx.message.author.id, 0)```
    
Pls help me
#

pls tell me what esactly is not correct and what i need to change

dull terrace
#

how does python know that you're inserting that into your database

shrewd apex
#

it's better if python don't know that way linter won't freak out ๐Ÿ—ฟ

slate swan
#

:/

shrewd apex
#

and use the cursor to execute SQL queries

slate swan
#

then how should i make the code?

dull terrace
slate swan
#

do u mind just giving me the code?

dull terrace
#

okay i'll give you the code, but you have to finish updating the 3k lines of code for my bot

slate swan
#

gimme the code for create table and register command and ill learn the rest of SQL

vale wing
primal token
silk fulcrum
#

hmmm ok..

slate swan
#
async def register(ctx):
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute("""CREATE TABLE IF NOT EXISTS userinfo (
                userid INTEGER,
                balance INTEGER
                """)

@bot.command(name="register")
async def register(ctx):
    con = sqlite3.connect('userinfo.db')

    cur = con.cursor()
    
    cur.execute("""INSERT INTO userinfo (userid, balance)
                VALUES(ctx.message.author.id, 0)
                """)```
vale wing
#

I asked AI to write an intro for "guide how to create a discord bot with python" and this is what it made

In this tutorial, we will be learning how to create a discord bot using the discord.py library. This library is extremely useful for creating bots in Python. However, before we get started, I want to let you know that this tutorial is for absolute beginners. If you don't know what a discord bot is, or if you don't know how to use the discord.py library, then this tutorial is not for you.

#

๐Ÿ˜‚

dull terrace
#

7739monkathink a paradox it is

vale wing
#

Two functions named the same

#

No

primal token
#

you shouldnt make a connection each call or use sqlite

slate swan
#

then help me change the code?

primal token
#

and why are you making a cursor, just use Connection.execute, it returns a cursor object if you nreallu need one

#

!pypi aiosqlite

unkempt canyonBOT
slate swan
#

...

#

Is there a way to convert random.choices list names to member object so i can mention them?

vale wing
#

First of all, why does the list have to consist of names

silk fulcrum
slate swan
#

i have integer in a db table ok?

primal token
#

you can but you shouldn't.

silk fulcrum
dull terrace
vale wing
#

What kind of integer

slate swan
#

i want the bot to choose some random people through that integer. So for example, if the int is 5, the bot will choose 5 random people. I did that with random.choices(list, k=data[2]).

#

And i stuck there

primal token
vale wing
#

The list can be ctx.guild.members, you will get the list of Member objects and will be able to do whatever you want with them

primal token
#

if you want to use attributes on the partial object its just hectic

slate swan
#

I cant store the ids at that point of my code

dull terrace
#

why not

slate swan
#

something like this?

vale wing
#

Yeah I think just don't redefine list builtin plz

slate swan
#

i'll just change the variable

dull terrace
#
list = dict```
๐Ÿ”ฅ
primal token
dull terrace
#

!e

list = dict
jeff = list([("will", "this"), ("work", "hmm")])
print(jeff)
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

{'will': 'this', 'work': 'hmm'}
primal token
#

use parametization and instantiation to make it worse

silk fulcrum
# dull terrace ```py list = dict``` ๐Ÿ”ฅ
from typing import Dict, Coroutine, Any, Callable, Awaitable, MutableMapping, Protocol, TypeVar

R = TypeVar('R')

good: Dict[Dict[Dict[tuple[Coroutine[Any, Any, None]], list[Any]], Dict[Callable[Callable[..., R]], Protocol[R]]], tuple[Dict[list[Dict[MutableMapping[str, R], Awaitable[R]]], float]]] = diy```
dull terrace
primal token
#

why annotate the variable and using tying.Dict, just use dict and instantiation to make it cursed

#

iirc typing.Dict cant even be instantiated

dull terrace
#

why have you got curly brackets around this getpuuid['data'][0]['players']['red'][1]['currenttier_patched']

primal token
dull terrace
#

!e

banana = {"this": 1, "is": 2, "a": 3, "dictionary": 4}
print(banana["this"])
if banana["this"] == 1:
  print("does this help?")
print({banana["this"]})
if {banana["this"]} == 1:
  print("this wont print")```
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | does this help?
003 | {1}
dull terrace
#

got there eventually

#

read the code i wrote again and pay attention to curly brackets and what it prints

#

there is no way the console output for {getpuuid['data'][0]['players']['red'][1]['currenttier_patched']} is "Diamond 1"

slate swan
#

how get ctx of other server?

#

in this code py @bot.command('role') @commands.has_permissions(administrator=True) #permissions async def role(ctx, user : discord.Member, *, role : discord.Role): if role in user.roles: await user.remove_roles(role) #removes the role if user already has await ctx.send(f"Removed {role} from {user.mention}") else: await user.add_roles(role) #adds role if not already has it await ctx.send(f"Added {role} to {user.mention}")

slate swan
#

nvm fixed

junior verge
#
embed.add_field(name="Created at:", value=f"<t:{int(member.created_at.timestamp().timestamp())}:f>")
silk fulcrum
junior verge
#

oh lmao

#

didn't see that haha

mossy jacinth
silk fulcrum
#

class must not be inside the cog

mossy jacinth
#

how can i do it then?

silk fulcrum
shrewd apex
#

!e

class A:
    class B:
        y = 7
    def foo(self):
        x = self.B()
        print(x.y)
c = A()
c.foo()
unkempt canyonBOT
#

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

7
shrewd apex
#

u could do self.uno

silk fulcrum
#

well yes... but what's the point? why not make class outside?

shrewd apex
#

idk pithink

spring flax
#

If I have this ```py
class SomeView(discord.ui.View):
def init(self, message: .Message):
super().init()

@discord.ui.Button(label="label", url=...)
How would I set the button url to `message.jump_url`?
silk fulcrum
#

url=message.jump_url

hushed galleon
#

set it during init by modifying the .url attribute on your function

spring flax
silk fulcrum
spring flax
hushed galleon
#

on instantiation, dpy looks for functions decorated with button() and replaces them with Button instances, which means you can edit those buttons afterwards by modifying them directly

unkempt canyonBOT
#

discord/ui/view.py lines 171 to 179

def _init_children(self) -> List[Item[Self]]:
    children = []
    for func in self.__view_children_items__:
        item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__)
        item.callback = _ViewCallback(func, self, item)
        item._view = self
        setattr(self, func.__name__, item)
        children.append(item)
    return children```
silk fulcrum
hushed galleon
#

yeah thats a typo

#

ah the decorator form actually doesnt allow url in the first place

silk fulcrum
#

why? ๐Ÿ˜ณ

#

oh wait yeah it does not

hushed galleon
#

there's no point for a link button to have a callback, so ig they disallowed that syntax entirely

silk fulcrum
#

i thought i used it and it work

silk fulcrum
hushed galleon
#

if you ever needed to put url buttons anywhere other than the end you'd have to clear_items() and add every button back, which is a little bit inconvenient

slate swan
#

Master why are you awake

silk fulcrum
slate swan
#

is it 4 PM for you?

silk fulcrum
#

yes it is

slate swan
#

oh

#

nvm then

#

it's 6 am here

silk fulcrum
#

UTC-7 moment

hushed galleon
#

i was up at 2am tackling readthedocs's build process, literally couldnt find any documentation about the problem i very easily stumbled into until i made a guess and it fixed itself

spring flax
#

If I have ```py
class MyClass(discord.ui.Button):
...
await myfunction()

class Bookmark(commands.Cog):
...
async def myfunction():
...

what are the ways I can access myfunction in the `MyClass`?
cold oyster
#

@dull terrace

#

You still there? Sorry for the ping by the way

dull terrace
#

yeah whats up

cold oyster
silk fulcrum
#

@spring flax

  • you do await myfunction() whereas it is not async
  • myfunction has to be a classmethod if you want to use it via Bookmark.myfunction()
  • do from __future__ import annotations to access the class that is in defined in future
cold oyster
#
@client.slash_command(name="echo", description="Send a text message through the bot")
async def echo(ctx, *, text=None):
    await ctx.send(text, ephemeral=False)```

It's because of this little guy
robust fulcrum
#

Guys can anyone suggest me good command idea (useful)

cold oyster
robust fulcrum
#

Bruh

#

How is it ot

cold oyster
#

No related to code lmao

dull terrace
#

and it should be text:str

cold oyster
#

They want a idea

cold oyster
silk fulcrum
robust fulcrum
#

It's related to discord bots

silk fulcrum
#

where is word "code"

cold oyster
robust fulcrum
hushed galleon
cold oyster
#

But if I add it again it just-

spring flax
dull terrace
#

typed up the code as i said to correct it and it worked on my bot

hushed galleon
dull terrace
#

i swear to god

silk fulcrum
cold oyster
robust fulcrum
cold oyster
silk fulcrum
robust fulcrum
#

for what?

silk fulcrum
#

idk

robust fulcrum
#

Eval don't need database

cold oyster
silk fulcrum
#

no, in your bot, not for eval

dull terrace
robust fulcrum
#

I using sqlite for my afk and prefix command

silk fulcrum
unkempt canyonBOT
#

@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.

this is eval
cold oyster
dull terrace
#

you're using disnake right?

cold oyster
cold oyster
flat swallow
silk fulcrum
dull terrace
#

it can't be to do with that code then, what other code you using

robust fulcrum
cold oyster
silk fulcrum
#

to execute sql queries from messages

flat swallow
silk fulcrum
robust fulcrum
flat swallow
#

It should be correct

cold oyster
robust fulcrum
cold oyster
#

and put the new one, Give it a try

flat swallow
cold oyster
#
import disnake as discord
from disnake.ext import commands

client = commands.InteractionBot()

@client.event
async def on_ready():
    print("Ready!")


@client.slash_command(name="ping", description="Get the latency of bot.")
async def ping(ctx):
    latency = round(client.latency * 1000)
    await ctx.send(f"Pong! The ping is `{latency}` ms", ephemeral=False)

@client.slash_command(name="echo", description="Send a text message through the bot")
async def echo(ctx, text:str):
    await ctx.send(text, ephemeral=False)

    
    


client.run("My token!")```
flat swallow
#

Still not working

cold oyster
flat swallow
robust fulcrum
#

Lol

cold oyster
#

;-;

robust fulcrum
#

Define it first

flat swallow
#

I am using replit and I have an environmental variable called TOKEN storing the value

cold oyster
robust fulcrum
flat swallow
cold oyster
robust fulcrum
#

Hmmm?

flat swallow
#

It alr is it is just redefined

#

afterwards for some reason

cold oyster