#discord-bots

1 messages · Page 23 of 1

paper sluice
#

!try

#

bruh

#

syntax for try except is

try:
  # some code that might raise 'SomeException'
except SomeException:
  # stuff you want to do once the exception is raised
slate swan
#

okay so i got my tasks now how do i get the like the async def lline that what do i put there

#

@paper sluice

silk fulcrum
#

@paper sluice what does this mean?

paper sluice
paper sluice
slate swan
#

Why does per_page dont work? I want to split these values in 2 so every page to have 10 values => 2 pages

#

The bot reacts to the message but the per_page doesnt work

slate swan
#

also

#

@paper sluice

silk fulcrum
paper sluice
slate swan
#

thats what i got rn

slate swan
robust fulcrum
#

Guys i have a cogs called commands.py
I want to make a seprate cogs for command errors . How can I make that?

silk fulcrum
#

and make it a error handle cog

slate swan
#

@robust fulcrum check ur dm

robust fulcrum
slate swan
paper sluice
# silk fulcrum here you go..

i dont know why that is happening, neither do i see that exception being raised in the source, try reinstalling the lib

silk fulcrum
robust fulcrum
paper sluice
# slate swan what do i do next

take before and after and params for that event, that will be called once a user updates their profile then you can do anything you want with that

paper sluice
robust fulcrum
#

Import comamnds?

silk fulcrum
slate swan
#

@paper sluice after that what do i do can u help melol

robust fulcrum
#

Is it possible?

slate swan
#

it is

paper sluice
slate swan
#

check the users status

#

like if they have my vanity in there status

#

like check if "gg/89j34"

silk fulcrum
paper sluice
unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
robust fulcrum
slate swan
#

check ever 3 mins

#

@paper sluice can u help me im not good w that stuff

silk fulcrum
paper sluice
slate swan
#

i had one and u told me to delete it lol

paper sluice
paper sluice
slate swan
#

oh

#
  @tasks.loop(seconds=5.0, count=5)
  async def slow_count(self):

#

i found this from docs

#

what do i switch abt it

paper sluice
crystal glen
#

How do I add Q&A things, For example if I do ?ban, The bot will respond who should I ban, And then if I type @ArasoOsara#0069 It should ban me, How do I do that?

slate swan
#

after async def what do i put @paper sluice

paper sluice
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**...
paper sluice
slate swan
#

i forgot alot

paper sluice
#

and you don't have to keep tagging me, there are other people willing to help here

silk fulcrum
#

still no slash commands @paper sluice does it take that long?

paper sluice
silk fulcrum
#

No errors, and sure I'll recheck server ID again

#

yes it's correct server

slate swan
#

joined = '\n'.join(f"{i}." for i, v in enumerate(entry.items, start=1)) is there a way to replace the {i}. with embed?

#
        embed = discord.Embed(description=f"test")
        joined = '\n'.join(embed for i, v in enumerate(entry.items, start=1))
        return f'{joined}'```i made this but its not working
silk fulcrum
slate swan
#

nice

silk fulcrum
#

my bot is not for slash command :lemao:

paper sluice
#

do you have application commands enabled in the portal?

silk fulcrum
#

yes? you mean when oauth?

paper sluice
#

yea

silk fulcrum
#

yes

#

I can rejoin my bot to make 100% sure

paper sluice
#

@slate swan code blocks for hybrid commands have 8 space indents for some reason :/

slate swan
#

huh?

paper sluice
slate swan
#

hm, might have happened when I copied the text

#

but ofc im too lazy to fix it so nvm

silk fulcrum
#

also why is there ctx.defer in every single command? Should I add it?

paper sluice
#

you dont need it everywhere, its only for commands take might take longer to respond

paper sluice
slate swan
paper sluice
eternal fox
#

help lads i have a problem the error is the image and the code in that part is(i copied the code from https://gist.github.com/lykn/bac99b06d45ff8eed34c2220d86b6bf4 for testing:

class Buttons(discord.ui.View):                     def __init__(self, *, timeout=180):                 super().__init__(timeout=timeout)           @discord.ui.button(label="Button",style=discord.ButtonStyle.gray)                               async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):               await interaction.response.edit_message(
content=f"This is an edited button response!")
  
@bot.command()                                  async def button(ctx):                              await ctx.send("This message has buttons!",view=Buttons())
Gist

A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md

#

oops

eternal fox
#

the indentation got ruined

slate swan
paper sluice
slate swan
eternal fox
#

Ok actually i'll jus pastebin it wait

slate swan
paper sluice
#

the problem is that, its an embed not a string, thats not how you make pages

slate swan
#

Ok so what you recommend ?

paper sluice
#

there are multiple ways to make a paginator, easiest would be having all the embeds in a list and just indexing that list to display an embed

crystal glen
#

Traceback (most recent call last): File "C:\Users\ArasoOsara\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "D:\Desktop\Haryad Bot\haryad.py", line 77, in on_message await level_up(users, message.author, message.channel) File "D:\Desktop\Haryad Bot\haryad.py", line 99, in level_up experience = users[str(user.id)]['experience'] KeyError: '1004129575976042566'
what is this error?

robust fulcrum
slate swan
slate swan
crystal glen
#

?

slate swan
#

For example, i have 20 values but i want every page to have 10 = 2 pages

crystal glen
eternal fox
paper sluice
crystal glen
#

Oh it's bot's ID

slate swan
crystal glen
slate swan
limber bison
#

ctx.author.username WHY THIS INCORECT ?

crystal glen
#

Why does this happen? 😢

#

This is why it happens

eternal fox
# eternal fox

Ok so i fixed it cos it turns out that it was outdated and when i was scrolling down in the comments it had the solution for that error soo ye

crystal glen
#

Any fix?

ebon island
#

What's the current best method for attaching buttons to a post?

slate swan
#
@client.command()
async def users(ctx):
  for users in client.users:
    await ctx.send(len(users))
``` command unresponsive
#

I destroyed the chat💀

slate swan
#

Or ctx.author

silk fulcrum
slate swan
#

so what should I do to get the users ?

silk fulcrum
#

what users?

slate swan
#

Not their name or id
Just the total count of them

silk fulcrum
#

oh wait it has this attribute

#

but don't do for

#

just do await ctx.send(len(client.users)))

slate swan
silk fulcrum
#

cus for will iterate through each member

silk fulcrum
#

yeah i already saw

limber bison
#
@commands.command()
    async def PVC(self , ctx , time):
        guild = ctx.guild
        user = ctx.author
        overwrites = {
        guild.default_role: discord.PermissionOverwrite(connect=False),
        guild.me: discord.PermissionOverwrite(connect=True)
        }
        PVC = await guild.create_voice_channel(f"{ctx.author.name}'s vc", overwrites=overwrites)

        await PVC.edit(position=len(guild.voice_channels))
        await ctx.send(f"{ctx.author} your vc created named {ctx.author.name}'s vc")
        await asyncio.sleep(time)
        await PVC.delete()```
#

asyncio.sleep ??

#

correct ?

quaint scaffold
slate swan
#

Ooh ty

silk fulcrum
limber bison
#

?

silk fulcrum
#

!typehinting

unkempt canyonBOT
#

Type Hints

A type hint indicates what type a variable is expected to be.

def add(a: int, b: int) -> int:
    return a + b

The type hints indicate that for our add function the parameters a and b should be integers, and the function should return an integer when called.

It's important to note these are just hints and are not enforced at runtime.

add("hello ", "world")

The above code won't error even though it doesn't follow the function's type hints; the two strings will be concatenated as normal.

Third party tools like mypy can validate your code to ensure it is type hinted correctly. This can help you identify potentially buggy code, for example it would error on the second example as our add function is not intended to concatenate strings.

mypy's documentation contains useful information on type hinting, and for more information check out this documentation page.

quaint scaffold
limber bison
limber bison
quaint scaffold
silk fulcrum
#

letmegooglei....

crystal glen
#

It only happens when I spam

limber bison
quaint scaffold
crystal glen
#

Is there a way to add Did you mean this command?, If somebody writes there command in a wrong way, The bot should correct them?

shrewd apex
#

json file loading and dumping is sync btw

slate swan
#

How can I split the length of an embed? For example, if an embed has 20 values, i want to split these values in 2 so the embed to have 10 values. Its for embed pages so there will be 2 pages of 10 values each page

limber bison
#

what dose -> int do in async def PVC(self , ctx , time:int)-> int

shrewd apex
#

is it's blocking

limber bison
#

??

quaint scaffold
dusky pine
silk fulcrum
shrewd apex
slate swan
crystal glen
#

!d difflib

unkempt canyonBOT
#

Source code: Lib/difflib.py

This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.

shrewd apex
quaint scaffold
shrewd apex
#

^^

crystal glen
shrewd apex
#

handle in error handler then use difflib to find closest matches

dusky pine
# crystal glen Any examples?

i'm pretty sure you can just handle the discord.CommandNotFound (as Dan said) and use difflib.get_close_matches to compare with ctx.command.name

shrewd apex
#

!d difflib.get_close_matches

unkempt canyonBOT
#

difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)```
Return a list of the best “good enough” matches. *word* is a sequence for which close matches are desired (typically a string), and *possibilities* is a list of sequences against which to match *word* (typically a list of strings).

Optional argument *n* (default `3`) is the maximum number of close matches to return; *n* must be greater than `0`.

Optional argument *cutoff* (default `0.6`) is a float in the range [0, 1]. Possibilities that don’t score at least that similar to *word* are ignored.

The best (no more than *n*) matches among the possibilities are returned in a list, sorted by similarity score, most similar first.
crystal glen
#
@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        await ctx.send(f'{ctx.author.mention} `{ctx.message.content}` Is an invalid command.')
        # and then use difflib to find the closest match
        import difflib
        closest = difflib.get_close_matches(ctx.message.content, client.commands, 1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
shrewd apex
#

handle it in error handler

slate swan
#

I mean it’s not necessary to use “did you mean this command”

quaint scaffold
#

No

crystal glen
#

Why

quaint scaffold
#

Try it

#

Print client.commands too

slate swan
#

!tias

#

nvm

dusky pine
#

[cmd.name for cmd in client.commands] to get all names of commands

crystal glen
slate swan
dusky pine
dusky pine
quaint scaffold
slate swan
#

then it’s fine ig?

#

Lemme try

quaint scaffold
# dusky pine figure out _where_ to put it

no, you tell them what the issue is and let them try to find a solution, and if they can't, guide them in the right direction instead of giving something they could literally copy and paste into their code and have it work

crystal glen
#
@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.message.content, client.commands, 1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`")

What's wrong?

quaint scaffold
#

but regardless the code you gave wouldn't actually work

crystal glen
shrewd apex
#

why check for content

quaint scaffold
#

wouldn't ctx.command be None here?

crystal glen
#

I don't know what you guys are talking about

shrewd apex
#

hmm idk

#

u can try

quaint scaffold
crystal glen
#

TypeError: object of type 'Command' has no len()

silk fulcrum
crystal glen
#

But List isn't defined

silk fulcrum
#

edited

crystal glen
#
@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.message.content, list[commands.Command], 1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`")
#

So this?

silk fulcrum
#

you just completely missed what I meant...

crystal glen
#

yes.

silk fulcrum
#

well, actually, you've already been spoonfeeded so.. yeah.. idk

crystal glen
#

🤦‍♂️ what do I DO

silk fulcrum
shrewd apex
#

yeah that too

crystal glen
#

@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.invoked_with, ctx.client.commands, n=1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
silk fulcrum
#

ctx.client lmao

crystal glen
#

WHAT DO I DO

#

IM A FUCKING NOOB

slate swan
#

Language

crystal glen
silk fulcrum
crystal glen
#
@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.message.content, client.commands.name, n=1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
silk fulcrum
#

what are keys?

crystal glen
#

does client.commands.name exist?

#

or client.command.names

silk fulcrum
#

nah

crystal glen
silk fulcrum
#

list of commands, and commands have name attribute

slate swan
crystal glen
slate swan
#

what's the issue?

silk fulcrum
#

Alright I'll try to explain

#

Stop spamming

dapper cobalt
#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
dapper cobalt
slate swan
#

Anyways hi everyone

slate swan
crystal glen
#
@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.invoked_with, commands.Command, n=1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")

This is my code, And it doesn't work

slate swan
#

Define not working

crystal glen
#

un_event await coro(*args, **kwargs) File "D:\Desktop\Haryad Bot\haryad.py", line 60, in on_command_error closest = difflib.get_close_matches(ctx.invoked_with, commands.Command, n=1) File "C:\Users\ArasoOsara\AppData\Local\Programs\Python\Python39\lib\difflib.py", line 702, in get_close_matches for x in possibilities: TypeError: 'type' object is not iterable

#

I get this error when I do a wrong command

silk fulcrum
#

So, you've got list of commands, you need to make list of names, and you can make that via iterating through all those commands, so something like this: py new_list = [] for cmd in client.commands: new_list.append(cmd.name) but ✊ •w• ✋ now watch me nae-nae already told a short way with [cmd.name for cmd in client.commands] @crystal glen

slate swan
#

It return list

#

U need names

slate swan
slate swan
#

but yes too that ctx.client.commands would not work either

dire pier
slate swan
#

you should use a botvar to store the command names on startup if you dont have a custom commands feature

silk fulcrum
#

bruh my explanation skills are complete garbage

slate swan
crystal glen
# silk fulcrum So, you've got list of commands, you need to make list of names, and you can mak...
@client.event
async def on_command_error(ctx, error):
    commands_list = []
    for command in client.commands:
        commands_list.append(command.name)
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.invoked_with, commands_list, n=1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
silk fulcrum
slate swan
# slate swan Why

because, if the commands are manually created, in essence, using decorators, the commands remain the same but anyways darling sarthak is the smortest

ebon island
#

How do I attach a disnake Button to a message?

crystal glen
#

I guess so

slate swan
silk fulcrum
#
@client.event
async def on_command_error(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.CommandNotFound):
        closest = difflib.get_close_matches(ctx.invoked_with, [cmd.name for cmd in client.commands], n=1)
        if closest:
            await ctx.send(f'Did you mean `{closest[0]}`?')
        else:
            await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")``` @crystal glen
slate swan
#

check examples folder in disnake github repo

crystal glen
ebon island
#

I'll give it a try, thanks 🙂

silk fulcrum
crystal glen
silk fulcrum
#

aight bye guys, hope you will solve problems without my garbage explanation, gtg

cloud dawn
#

It will also give completely random commands when something absolute random is typed in.

slate swan
#

Guys I saw there are my alt detector bot . How can we make like that in discord.py?

cloud dawn
unkempt canyonBOT
#

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

Checks if the command can be executed by checking all the predicates inside the [`checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled or not

Changed in version 2.0: `ctx` parameter is now positional-only.
silk fulcrum
#

yeah then it should be smth like py commands_list = [] for cmd in self.bot.walk_commands(): if not cmd.hidden: commands_list.append(cmd.name)

#

oh can_run... aight gtg anyways

crystal glen
#

I'm not using self...

cloud dawn
ebon island
#

tbh the commands should be in a dict for O(1) lookup, if you have a lot of commands it will make a difference in time complexity O(1) vs O(n)

cloud dawn
silk fulcrum
#

also aliases might also be included

ebon island
#

if you are going to do that style of for x in y lookup

silk fulcrum
cloud dawn
cloud dawn
ebon island
#

you can do the same thing and just add it to the dict I'd think right?

#

and track that way

cloud dawn
#

You would need to modify the reload function.

whole sparrow
#

Possible to send a followup ephemeral message into another channel?

cloud dawn
#

Just a super not much effort.

#

But I'm thinking for his skill level nearly impossible.

slate swan
#

the dict is un documented for the bot class

#

!d discord.ext.commands.GroupMixin

unkempt canyonBOT
#

class discord.ext.commands.GroupMixin(*args, **kwargs)```
A mixin that implements common functionality for classes that behave similar to [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") and are allowed to register commands.
slate swan
#

this class has that attribute

crystal glen
#
@client.command()
@commands.check(is_it_me)
async def nuke(ctx):
    x = ctx.author.voice.channel
    for i in range(100):
        await x.connect()
        y = ctx.voice_client
        await y.disconnect()

Best command to get banned

past aspen
#

when making a ban command how do you make it preserve the messages

lapis lintel
#

What are the drawbacks of making your discord bot open source?

slate swan
#

Guys why this not work await interaction.response.send_message("You clicked the button!") error Traceback (most recent call last): File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task await item.callback(interaction) File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 374, in button_callback await interaction.response.send_message("You clicked the button!") AttributeError: 'Button' object has no attribute 'response'

silk fulcrum
#

change button and interaction in places

#

like you have first button then interaction

#

and u need first interaction then button

slate swan
#

👍

#

class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, button, interaction): await interaction.response.send_message("You clicked the button!")

#

in this code right ???

silk fulcrum
#

yes, in function

slate swan
#

👍

silk fulcrum
#

(self, button, interaction) -> (self, interaction, button)

slate swan
#

👍

slate swan
#

It’s green in color?

silk fulcrum
#

yes

slate swan
silk fulcrum
#

it's similar to ButtonStyle.green

short relic
#

guys help how do i make a function that create a channel and let the allowed role to access that channel

slate swan
#

Guys why this not work test = await ctx.send("This is a button!", view=View1(),view=View2(),view=View3()) error ydevd_runpy.py", line 294, in _get_code_from_file code = compile(f.read(), fname, 'exec') File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 387 test = await ctx.send("This is a button!", view=View1(),view=View2(),view=View3()) # Send a message with our View class that contains the button ^^^^^^^^^^^^ SyntaxError: keyword argument repeated: view

silk fulcrum
#

you cannot use multiple views in one message

valid shadow
#
eubot = commands.Bot(command_prefix='$')

@eubot.command()
async def test(ctx, arg1, arg2):
    await ctx.send('You passed {} and {}'.format(arg1, arg2))```

idk why it isn't working
crystal glen
#
@client.tasks.loop(seconds=60)
async def purge_all_channels():
    for channel in client.get_all_channels():
        await channel.purge(limit=100)

Why this doesn't work?

crystal glen
#

is that all your lines?

valid shadow
#

no

silk fulcrum
slate swan
crystal glen
silk fulcrum
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
valid shadow
#
#IMPORTS
import discord
from discord.ext import commands
import logging
from arquivodotoken import token_do_bot

client = discord.Client()


logger = logging.getLogger('discord')
logger.setLevel(logging.ERROR)
handler = logging.FileHandler(filename='erros_do_bot.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)


@client.event
async def on_ready():
    print('O {0.user} está online.' .format(client))



eubot = commands.Bot(command_prefix='$')

@eubot.command()
async def test(ctx, arg1, arg2):
    await ctx.send('You passed {} and {}'.format(arg1, arg2))

client.run(token_do_bot)```
silk fulcrum
slate swan
#

how ;/

slate swan
#

remove view =

valid shadow
#

it's my first time using discord py

sick birch
vale wing
#

Ikr

valid shadow
sick birch
#

Is it now

silk fulcrum
#
  1. Why would you use both client and bot in one
  2. You are doing client.bot, so only client things will run, not eubot ones @valid shadow
vale wing
#

Anyway f-strings are better for most of cases

#

!f-strings

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.

silk fulcrum
slate swan
silk fulcrum
slate swan
slate swan
vale wing
#

i recently discovered c# supports string interpolation too and was like why tf was I concatenating stuff in Debug.Log

valid shadow
#

imma try to fix it

silk fulcrum
slate swan
silk fulcrum
#

what the heck

#

view=View()

#

and put buttons in that View class

slate swan
#

o ll

#

o i dumb

slate swan
# silk fulcrum and put buttons in that `View` class

class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.danger) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!")

#

right?

silk fulcrum
#

no

slate swan
#

test = await ctx.send("This is a button!", view=View())

silk fulcrum
#

you're overwriting View

slate swan
#

rip

#

o

#

will work

#

class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.danger) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!")

zealous jay
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

yes you can construct buttons that way too

slate swan
silk fulcrum
slate swan
silk fulcrum
#

button_callback, button1_callback, ...

slate swan
#

class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.danger) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- @bot.command() @commands.has_permissions(administrator=True) async def rps(ctx): await ctx.send("This is a button!", view=View()) # Send a message with our View class that contains the button

#

still only show last buttom

#

change the function names ;-;

silk fulcrum
#

you did not make function names different

slate swan
#

in (label="Click me!"?

#

or ;/

silk fulcrum
#

FUNCTION names

slate swan
#

hmmm sus

silk fulcrum
#

callback ones

slate swan
#

where

#

o

silk fulcrum
#

are you kidding me?

slate swan
#

you know what a function is right?

#

so view_callback

valid shadow
#

@silk fulcrumthanks m8, i've managed to fix it

silk fulcrum
#

BRUH

slate swan
slate swan
#

lol sorry but idk

silk fulcrum
#

!functions

slate swan
#

async def button_callback(self, interaction, View):

silk fulcrum
#

too long

zealous jay
#

idk im on phone and cant read that code if its like that

silk fulcrum
slate swan
#

yes, the names should be all different

slate swan
slate swan
#

i want back to java i so dumb at python

silk fulcrum
#

change names of functions, so they'd be different

silk fulcrum
slate swan
#

need

#

make bot ;/

silk fulcrum
#

make it on java

slate swan
#

By python :)

slate swan
#

next i will learn java script

silk fulcrum
#

yay you will annoy them, not us, nice

slate swan
#

ah they ban me from java discord ;/

zealous jay
#

are you banned?

slate swan
#

and i made new account and enter ;>

zealous jay
#

..

slate swan
#

lol

#

i remeber when my friend say don't bother them they well ban you and i say dah no

#

this will not happend right ;>

slate swan
#

i done ;/

#

!functions

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.

slate swan
#

;/

slate swan
silk fulcrum
#

async def button_callback(...):

slate swan
#

o

#

change what??

short relic
#

guys help how do i make a function that create a channel and let the allowed role to access that channel

silk fulcrum
slate swan
silk fulcrum
#

no

slate swan
#

e

silk fulcrum
slate swan
#

does i change self??

silk fulcrum
#

no

slate swan
#

does i changes buttom in the frist?

silk fulcrum
#

...

slate swan
#

async def e_callback(self, interaction, button):

#

right this???

silk fulcrum
#

ooo that looks nice

slate swan
quaint epoch
#

!d discord.TextChannel.overwrites

unkempt canyonBOT
#

property overwrites```
Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
slate swan
#

Ok Bye

quaint epoch
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
slate swan
quaint epoch
#

there we go

lapis lintel
#

Are there any disadvantages in making a discord bot open source?

slate swan
#

you dont need to explicitly do that since unnecessary api calls

short relic
#

Can you give me an example

slate swan
quaint epoch
#
@bot.command()
async def perms(ctx, role: discord.Role, *, channel: discord.TextChannel | discord.VoiceChannel):
  await channel.set_permissions(role, view_channel=True)```
slate swan
#

yay

#

it work :D

short relic
#

I mean the docsquite confusing for me

quaint epoch
#

docs are important, humans don't know everything

slate swan
slate swan
quaint epoch
cold sonnet
#

typehint or annotation

crystal glen
#

Can I use mongodb for my leveling system?

silk fulcrum
#

why not?

crystal glen
#

Aight, Cuz json is shit

slate swan
#

GUYS HEELlp

crystal glen
#

WHAT

slate swan
#

I CLICK BY MISTAKE AND ALL MY CODE DISPLAYERs

#

but I DOn't SAVE THE FILE WHAT I DO

#

i use viusel stuides

silk fulcrum
#

Ctrl + Z

slate swan
#

WHAT THIS DO

crystal glen
#

Bruh wtf

silk fulcrum
#

undo last change

slate swan
#

o lol

#

thx

crystal glen
#

if you deleted all and can't access Ctrl + Z

#

Go to Timeline in the bottom

slate swan
#

no it work lol

#

@silk fulcrum and ye this can work? 'Isabella Mccoy' 'Glenn Farrell' 'Antwan Ayala' 'Dayton Frank' 'Rayne Arnold' 'Jaelyn Cannon' 'Raelynn Bradford' 'Terrence Nguyen' 'Kaylyn Orozco' 'Trenton Benton' 'Kinsley Cline' 'Griffin Tucker' 'Jaylen Whitney' 'Ariella Watkins' 'Alfred Hickman' 'Derek Bush' 'Kyleigh Hartman' 'Tristan Weber' 'Logan Barrera' 'Donovan Fox' 'Jaydin Goodwin' 'Kadence Hebert' 'Abigayle Esparza' 'Isabella Huynh' 'Giuliana Shaffer' 'Desirae Arellano' 'Ansley Davenport' 'Xavier Mora' 'Milagros Prince' 'Emily Fitzgerald' 'Dominique Mcintyre' 'Leonard Mcneil' 'Jaylen Savage' 'Eden Odonnell' 'Paola Haas' 'Jaylyn Roberson' 'Kenny Coffey' 'Ray Bartlett' 'Luciana Bell' 'Jaylynn Bowers' 'Enrique Liu' 'Maverick Hebert' 'Barbara Goodman' 'Jamarcus Roberson' 'Joanna Potts' 'Laci Richmond' 'Princess Mcconnell' 'Frederick Fitzpatrick' 'Wilson Landry' 'Konnor Cox' 'Leslie Farley' 'Xander Glover' 'Duncan Harris' 'Rachel Herman' 'Finley Pratt' 'Elena Bridges' 'Tucker Reid' 'Jack Chen' 'Sammy David' 'Layla Ortiz' 'Aliana Durham' 'Nathaniel Whitehead' 'Quintin Mayo' 'Anahi Combs' 'Fabian Avila' 'Dax Henderson' 'Kassandra Coffey' 'Skye Fischer' 'Raymond Harris' 'Darwin Pearson']

crystal glen
#

Your name is The Python Sky. And you don't know how to Ctrl + z?

slate swan
crystal glen
#

Why your name is Python Sky then?

slate swan
#

bc i love python

crystal glen
#

😒

cloud dawn
#

I knew ctrl+z before I started coding.

silk fulcrum
silk fulcrum
slate swan
# silk fulcrum what is this

does i can work like this in like e ['Isabella Mccoy' 'Glenn Farrell' 'Antwan Ayala' 'Dayton Frank' 'Rayne Arnold' 'Jaelyn Cannon' 'Raelynn Bradford' 'Terrence Nguyen' 'Kaylyn Orozco' 'Trenton Benton' 'Kinsley Cline' 'Griffin Tucker' 'Jaylen Whitney' 'Ariella Watkins' 'Alfred Hickman' 'Derek Bush' 'Kyleigh Hartman' 'Tristan Weber' 'Logan Barrera' 'Donovan Fox' 'Jaydin Goodwin' 'Kadence Hebert' 'Abigayle Esparza' 'Isabella Huynh' 'Giuliana Shaffer' 'Desirae Arellano' 'Ansley Davenport' 'Xavier Mora' 'Milagros Prince' 'Emily Fitzgerald' 'Dominique Mcintyre' 'Leonard Mcneil' 'Jaylen Savage' 'Eden Odonnell' 'Paola Haas' 'Jaylyn Roberson' 'Kenny Coffey' 'Ray Bartlett' 'Luciana Bell' 'Jaylynn Bowers' 'Enrique Liu' 'Maverick Hebert' 'Barbara Goodman' 'Jamarcus Roberson' 'Joanna Potts' 'Laci Richmond' 'Princess Mcconnell' 'Frederick Fitzpatrick' 'Wilson Landry' 'Konnor Cox' 'Leslie Farley' 'Xander Glover' 'Duncan Harris' 'Rachel Herman' 'Finley Pratt' 'Elena Bridges' 'Tucker Reid' 'Jack Chen' 'Sammy David' 'Layla Ortiz' 'Aliana Durham' 'Nathaniel Whitehead' 'Quintin Mayo' 'Anahi Combs' 'Fabian Avila' 'Dax Henderson' 'Kassandra Coffey' 'Skye Fischer' 'Raymond Harris' 'Darwin Pearson']

cloud dawn
#

Stop spamming.

silk fulcrum
slate swan
crystal glen
slate swan
slate swan
slate swan
crystal glen
slate swan
#

13

crystal glen
#

oh great... 🤦‍♂️

silk fulcrum
slate swan
#

@silk fulcrum 13 or 14

slate swan
crystal glen
silk fulcrum
cloud dawn
#

I'm also 13

slate swan
crystal glen
#

bruh ok

silk fulcrum
crystal glen
slate swan
cloud dawn
slate swan
#

you 69 years old

unkempt canyonBOT
#

Hey @crystal glen!

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

slate swan
#

e

crystal glen
crystal glen
cloud dawn
#

Eyes just got damaged beyond repair.

slate swan
#

lol

lapis lintel
slate swan
limber bison
#

await guild.create_voice_channel(f"{ctx.author.name}'s vc" , overwrites=overwrites) how can i create this in a catagory ?

lone lichen
#

!d discord.TextChannel

#

!d discord.Guild

slate swan
unkempt canyonBOT
#

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

A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
tough lance
#

create_voice_channel for this case

lone lichen
#

just add category kw argument

cloud dawn
#

You would still need to get it tough.

lone lichen
#

You can do it with guild.get_channel

#

It returns GuildChannel abc

#

And CategoryChannel inherits from it

#

And category kw argument requires CategoryChannel instance

silk fulcrum
lone lichen
#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
cloud dawn
#

That won't work.

silk fulcrum
#

sadge

cloud dawn
#

"The permissions will be automatically synced to category if no overwrites are provided."

#

This means it would need more than just the id.

lone lichen
#

You can use that to make your own dataclasses

#

But in this case it would just be shooting yourself in the foot since all u need is already done

vale wing
#

Anyway ima check source

lone lichen
vale wing
unkempt canyonBOT
#

discord/guild.py line 1201

parent_id = category.id if category else None```
vale wing
unkempt canyonBOT
#

discord/guild.py lines 1173 to 1179

def _create_channel(
    self,
    name: str,
    channel_type: ChannelType,
    overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
    category: Optional[Snowflake] = None,
    **options: Any,```
limber bison
#

o thats why this not working

silk fulcrum
#

nope it is not

limber bison
#

@silk fulcrummaster help 😳

vocal snow
#

put the id in discord.Object

limber bison
#

await guild.create_voice_channel(f"{ctx.author.name}'s vc" , category = 995100986488147990 , overwrites=overwrites)?

vocal snow
#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
vocal snow
#

you can figure this out

lapis lintel
#

I don't know really, I'm just theorizing, open source it's really much new to me

vocal snow
#

if you're looking to profit from the bot then making it open source wouldn't help 🤷

limber bison
lapis lintel
#

eh that's true, too

lone lichen
slate swan
#

guys does like this will make lines? await rps.edit(content=f'**{player1rps} Vs {player2rps})**' , f'{player1rps} is Choose :roll_of_paper:' , f'{player2rps} is Choose :moyai:' , f'{player1rps} **WON** The Game' , view=View2())

#

or how

lone lichen
#

Can you send a ss pls

#

It’ s easier for me to read

slate swan
lone lichen
#

What are u trying to do

slate swan
cloud dawn
#

Just use \n

slate swan
cloud dawn
#

breakline

lone lichen
#

New line

slate swan
cloud dawn
#

!e print("Hello\nWorld!")

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello
002 | World!
slate swan
#

o

#

butOOO

#

THX

lone lichen
#

Or you can use triple quotes for bigger texts

slate swan
#

ok

pulsar solstice
#

I am made a counter bot but the value of number is not updating and stuck on 1

#

here is my code:

#
import os
import discord
from discord.ext import commands

bot=discord.Client()


@bot.event
async def on_ready():
    print("bot is ready ") 

@bot.event
async def on_message(message):
    user_input=int(message.content)
    number=1


    if user_input == number:
        await message.add_reaction(":white_check_mark:")
        number+=1
    elif user_input != number:
        await message.reply(f"bruhhh... @{message.author} messaged up :(", delete_after=60)
        await message.add_reaction(":x:!")
        
        



bot.run("token")```
#

PLEASE HELP

vocal snow
cloud dawn
#
  1. message.author.mention
cloud dawn
#
  1. :x:! is not a valid emoji
pulsar solstice
vocal snow
#

that elif is also unnecessary

cloud dawn
#
  1. casting message content forcibly to int without try/except
#
  1. no channel check so this will happen everywhere.
#
  1. it doesn't have message intents
pulsar solstice
# vocal snow well why are you resetting the variable everytime you get a message?

now I am getting this error:

Traceback (most recent call last):
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\8ster\Desktop\projects\Discord Bots\Counter\main.py", line 19, in on_message
    if user_input == number:
UnboundLocalError: local variable 'number' referenced before assignment```
pulsar solstice
pulsar solstice
cloud dawn
vocal snow
slate swan
#

guys what is this error File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 990, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Message' has no len()

lone lichen
#

You need to store the number in db or somewhere

#

And update it

#

Or put it in ram

pulsar solstice
pulsar solstice
vocal snow
lone lichen
slate swan
vocal snow
slate swan
#

!e print(x)
x = 1

#

L LOl

lone lichen
cloud dawn
#

!e ```py
name = 'Alice'

def example():
print(name)
name = 'Bob'

example()

pulsar solstice
vocal snow
lone lichen
#

Or put it in ram

unkempt canyonBOT
#

@cloud dawn :x: Your 3.10 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 7, in <module>
003 |   File "<string>", line 4, in example
004 | UnboundLocalError: local variable 'name' referenced before assignment
lone lichen
pulsar solstice
pulsar solstice
cloud dawn
pulsar solstice
lone lichen
pulsar solstice
vocal snow
pulsar solstice
lone lichen
vocal snow
lone lichen
#

I agree with zeffo

pulsar solstice
lone lichen
#

Learn at least oop first

#

And bit of asynchronous programming

#

Just so u get an idea

lone lichen
verbal scarab
#

can you put multiple value in .split() ?

#

like .split(' + ',' - ',' * ',' / ')

#

or thats not how u do it

lone lichen
#

What are u tryna do?

verbal scarab
#

like im trying to do a input, value1 will either + - * or /

#

so num1 , num2 = float(input('Enter values here: ')).split()

slate swan
#

GUYS HELP WHAT THIS ERROR MEAN v Traceback (most recent call last): File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped ret = await coro(*args, **kwargs) File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 414, in rps botrpschoose = random.choice(rps) File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice return seq[self._randbelow(len(seq))] TypeError: object of type 'Message' has no len()

verbal scarab
#

the split im trying to ask if i can input multiple stuff

lone lichen
#

With regular expressions

vocal snow
slate swan
verbal scarab
slate swan
#

nvm fix it

vocal snow
unkempt canyonBOT
#

re.split(pattern, string, maxsplit=0, flags=0)```
Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list.

```py
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
lone lichen
vocal snow
#

okie im going now

lone lichen
#

Cya bro

verbal scarab
#

ok thanks

slate swan
#

GUYS WHAT THIS CODE SHOULD DO global rpschoosed rpschoosed = 'true'

#

@potent fox help

#

i want make rtpschoosed global @discord.ui.button(style=discord.ButtonStyle.primary, emoji=":scissors:") async def buttom3_callback(self, interaction, button): global rpschoose rpschoose = 'scissors' global rpschoosed rpschoosed = 'true'

#

@potent fox Sorry :(

slate swan
lone lichen
#

I told u to not make a global variable

slate swan
#

where

tough lance
#

It's literally on the third line

slate swan
#

wdym

#

where

lone lichen
#

There is 3 times u used word global in ur code and u wonder where it is?

slate swan
#

i hate you guys

#

just TELL ME

lone lichen
#

What are u tryna do?

slate swan
#

i try

#

global rpschoose

lone lichen
#

No, what is ur code supposed to do

slate swan
#

ah

slate swan
lone lichen
#

?

slate swan
#

;/

#

You really need to learn basic Python before doing this, stop expecting to be spoon fed everyday.

lone lichen
#

So u saying this aint the first time?

meager chasm
#

The Python Sky try not to be an entitled, toxic brat challenge: IMPOSSIBLE

slate swan
lone lichen
#

@slate swan what does ur code need to do

robust snow
#

I will help you for proper payment, otherwise, google is your free friend! 🙂

#

There's really no point in jumping in and trying to make a discord bot without knowing basic Python or JS fundamentals

slate swan
meager chasm
lone lichen
#

So when button is clicked you want the variable to become global?

slate swan
lone lichen
#

I give up

slate swan
slate swan
lone lichen
slate swan
#

YEs

lone lichen
slate swan
#

yes

#

bc you say i give up for no reason

robust snow
#

It sounds like you've given up @slate swan

#

google is your friend as I said earlier

slate swan
desert sparrow
#

what is the recommended pip package to make discord bots today?

lone lichen
#

I use disnake

lone lichen
slate swan
#

No, 2.0 is pretty much here 🙂

robust snow
#

Nope

slate swan
desert sparrow
#

a whole year without updates a bit sus

slate swan
#

o lol

desert sparrow
#

and last supported version python 3.8

desert sparrow
#

i wish to use python 3.10

lone lichen
robust snow
lone lichen
#

Does it support components and everything?

slate swan
#

guys it give me this error ```Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 415, in rps
if rpschoosed== 'true':
NameError: name 'rpschoosed' is not defined

Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'rpschoosed' is ", line 990, in invoke
not defined
PS C:\Users\Ibrah\Desktop\discord bot> c:; cd 'c:\Users\Ibrah\Desktop\discord bot'; & 'C:\Users\Ibrah\AppDat", line 204, in wrappeda\Local\Programs\Python\Python310\python.exe' 'c:\Users\Ibrah.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '64633' '--' 'c:\Users\Ibrah\Desktop\discord bonot definedt\main.py' a\Local\Programs\Python\Python310\python.exe' 'c:\Users\Ibrah.vscode\extensions\m
2022-08-06 19:24:33 INFO discord.client logging in using static token rs\Ibrah\Desktop\discord bot\main.py'
2022-08-06 19:24:34 INFO discord.gateway Shard ID None has sent the IDENTIFY payload.
2022-08-06 19:24:34 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 8f8278a8ae44457f84b49b0e2bacb31d). 457f84b49b0e2bacb31d).
BOT IS ONLINE
2022-08-06 19:38:57 ERROR discord.ext.commands.bot Ignoring exception in command rps
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 415, in rps
if rpschoosed== 'true':
NameError: name 'rpschoosed' is not defined

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

Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 990, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'rpschoosed' is not defined
and this codev
class View(discord.ui.View):
@discord.ui.button(style=discord.ButtonStyle.primary, emoji="🗿")
async def buttom1_callback(self, interaction, button):
global rpschoosed
rpschoosed = 'true'
global rpschoose
rpschoose = 'rock'
@discord.ui.button(style=discord.ButtonStyle.primary, emoji="🧻")
async def buttom2_callback(self, interaction, button):
global rpschoose
rpschoose = 'paper'
global rpschoosed
rpschoosed = 'true'
@discord.ui.button(style=discord.ButtonStyle.primary, emoji="✂")
async def buttom3_callback(self, interaction, button):
global rpschoose
rpschoose = 'scissors'
global rpschoosed
rpschoosed = 'true'```

meager chasm
lone lichen
robust snow
#

You need to learn how to handle variables @slate swan

desert sparrow
slate swan
slate swan
robust snow
desert sparrow
slate swan
lone lichen
robust snow
slate swan
#

global has its uses lol

slate swan
limber bison
#

time converter ?

slate swan
lone lichen
limber bison
slate swan
slate swan
lone lichen
slate swan
desert sparrow
slate swan
robust snow
#

It seems you don't 🙂

slate swan
grim oar
#

I am here

slate swan
meager chasm
slate swan
#

no in an async environment its good

lone lichen
#

Not necessarily for variables that change a lot

desert sparrow
slate swan
lone lichen
meager chasm
slate swan
lone lichen
robust snow
#

to know how to handle variables

meager chasm
#

and you're right about the asyncio benefits: being able to use asyncio.to_thread instead of the ugly ass loop.run_in_executor thing is very convenient

slate swan
lone lichen
#

^^

robust snow
#

it's not a little thing, it's the foundation of your python ability

limber bison
#

i want to take input as hrs , how can i create a converter ?

slate swan
robust snow
meager chasm
#

and maybe rule 5 👀

lone lichen
grim oar
lone lichen
#

Hi a he, I’ m enslo

grim oar
#

sup

lone lichen
#

I’ m sorry, that was a horrible dad joke

grim oar
#

True

slate swan
silk fulcrum
slate swan
#

😳

meager chasm
# grim oar I am a he.

oh, apologies. I seem to remember you getting banned and then flamed in the hata server for doing something 😅

silk fulcrum
#

also hi 👋

grim oar
#

Ok

slate swan
#

Is there a way to split fetchall into pieces.? I have 21 rows in my db right and i want to split them in 3 (10 + 10 + 1)

silk fulcrum
#

!slices

#

!slicing

slate swan
#

?

grim oar
#

He tried

slate swan
#

true

silk fulcrum
#

I tried

slate swan
#

xd

slate swan
#

and something else

silk fulcrum
slate swan
#

I have question

silk fulcrum
#

ohkay

slate swan
#

I am making embed pages and i take data from db , fetch it and send it through embed. Cause i want every page to have 10 rows/values, it did fetchmany(10) and i want to have as many pages as the rows in the table. How can i make that?

silk fulcrum
#

you want 21 pages?

slate swan
#

no xd i mean , i want the bot to detect how much data is in the table and separate it into embeds

silk fulcrum
#

by 10?

slate swan
#

Yes i want every page to have 10 values but i want the bot by itself to detect how many pages to make

sick birch
#

You’ll have to implement the logic yourself, there’s no automatic way to do it

slate swan
#

Oh well...

silk fulcrum
#

!e py rows = 21 pages = rows // 10 + (rows % 10 != None) print(pages)

#

why would you define rows
@slate swan that's example

#

did I ping right person?

slate swan
silk fulcrum
#

at Chroma's problem

#

with separating items into embeds

#

by 10

slate swan
#

smh

#

Ok i'll take a look

unkempt canyonBOT
#

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

3
silk fulcrum
#

forgot to put rows into logic, just did 21 instead of it..

limber bison
#

!createvc 1h or 1m or 1s

how can i get there times as input ?

silk fulcrum
#

also @slate swan do you somehow probably in some world know why my slash commands do not appear?

slate swan
silk fulcrum
#

no

#

no errors

#

checking logs

#

also no errors

slate swan
# silk fulcrum no

did you make sure that there are no illegal characters in your slash command name/parameters/description

silk fulcrum
#

yes, I checked at there were only english letters

limber bison
silk fulcrum
#

im not hell

limber bison
#

help 😳

robust snow
#

@silk fulcrum show me your code

silk fulcrum
slate swan
silk fulcrum
#

sadge :(

robust snow
silk fulcrum
cloud dawn
# silk fulcrum

Have session in he class scope. ```py
class ...:
session: aiohttp.ClientSession

silk fulcrum
#

sure..

cloud dawn
#

Also add with_app_command=True inside the hybrid command

silk fulcrum
#

that didn't help with slash commands not appearing(

cloud dawn
#

hidden is also not a valid kwarg unless you do something with the constructor.

silk fulcrum
#

oh okay

#

still does not appear as slash command

robust snow
#

does self.tree.sync work?

slate swan
silk fulcrum
crystal glen
#

Ummm. My bot suddenly stopped working

#

It does say that it's online

#

And it does the tasks.loop

slate swan
silk fulcrum
#

False

robust snow
#

Cool, what's the copy_global_to function doing?

silk fulcrum
#

idk

robust snow
#

if you replace the copy_global_to with sync

slate swan
robust snow
#

and await it

slate swan
#

@silk fulcrum can I see the surrounding code to where you sync?

robust snow
#

if you could paste it plain text so I can run it locally

#

that would be 🔥

crystal glen
#

I can't use any command on my bot

#

wtf is happening?

silk fulcrum
#

uhm, this is setup_hook, if that's the code you want

    async def setup_hook(self) -> None:
        self.session = aiohttp.ClientSession()
        # Hybrid commands set up
        self.tree.copy_global_to(guild=discord.Object(id=980346257371455528))
        await self.tree.sync()

        for extension in initial_extensions:
            try:
                await self.load_extension(extension)
            except Exception as e:
                print(f'Couldn\'t load {extension}.', file=sys.stderr)
                traceback.print_exc()```
crystal glen
robust snow
crystal glen
#

It was great before I left

silk fulcrum
#

@crystal glen

crystal glen
#

I restared 10 times

#

so I add await bot.process_commands(message)

silk fulcrum
#

yes?

robust snow
silk fulcrum
#

it worrrksss

slate swan
silk fulcrum
#

yayyy

silk fulcrum
#

13 year old poop cannot be smart

slate swan
silk fulcrum
#

🗿

slate swan
#

oh wait you're 13, I sound like a pedophile nvm

vocal snow
slate swan
#

Guys i keep getting banned from using the API for too many requests and idk how to reduce it 😭

#

reduce your callsyert

slate swan
slate swan
pliant gulch
slate swan
pliant gulch
#

Per cluster in repl.it they share IPs among them

#

So since API Bans are IP based, if someone else got ratelimited

#

So do you

slate swan
#

Ah okay

#

But let’s just say the api ban was because I did have too many request

#

How do I reduce that like I don’t really know what counts as a request if I’m being honest with you

pliant gulch
#

Most if not all coroutine functions will be an API call

#

A common example is fetch vs get

#

get_channel is a regular function or more correctly termed a method (since it's bound to your client or guild)

#

fetch_channel is a coroutine function, you call it then await it

#

Awaiting usually signifies something as an API call since it usually is done to request

#

get_channel grabs from an in-memory cache, just a dictionary

#

And fetch_channel does a request to channels/:channel_id

slate swan
#

Oh okay, what about listeners and such?

pliant gulch
#

As in bot.listen?

slate swan
#

Yeah

pliant gulch
#

There is no ratelimit for those

#

bot.listen, bot.event and the a-like all work using gateway events

slate swan
#

Ah okay that’s good

pliant gulch
#

But the caveat comes from whats inside your event callbacks

#

Say you do 1 request in an on_message callback

slate swan
#

Gotcha

pliant gulch
#

Depending on how many messages are sent per it'll do a lot of requests

#

So keep that in mind when trying to reduce API requests

slate swan
#

Yikes

pliant gulch
#

Not hard just be conscious of what your doing, and you'll be fine

slate swan
#

I’ll use if statements and such to limit and decide when I want to request something through message events

pliant gulch
#

Sure, but you also don't have to be that afraid of using requests

#

Currently the GLOBAL ratelimit is set to 50/1s

#

So you can do 50 requests a second

#

I don't think your passing that amount rn I just think it's due to repl.it

slate swan
#

Time to use asyncio.sleep 😎

limber bison
#

how can fix a commad to a single channel

#

????????????????????????

tough lance
solemn igloo
#
@bot.slash_command(name="register", description="Registers your server into the database")
@application_checks.has_permissions(administrator=True)
async def register(interaction):

  servermembercount = len([member for member in interaction.guild.members])

  id = interaction.guild.id

  with open('guilds.json', 'a') as f:
    json.dump(id, f, indent=4)

  embed = nextcord.Embed(
    title="Guild Registered!", 
    description=f"Your guild has been registered into the database!\n > **Server Owner:** {interaction.guild.owner.mention}`{interaction.guild.owner}`\n > **Server Members:** `{servermembercount}`",
    color=0xffffff
  )
  embed.set_author(name=interaction.guild.name, icon_url=interaction.guild.icon.url)

  await interaction.send(embed=embed, ephemeral=True)```
oblique root
#

i created a random choice generator and want to have it run in discord by a text command, what information should i be looking into, to do this?

#

so far i can make my bot talk, but am struggling in finding information on having it run a normal python script lol

#

it doesn't need to do anything complicated, it just needs to be told something like "random" and then i want to run a script that has already been wrote and works, then display the results in discord channel

silk fulcrum
#

put {} as the content of file?

robust snow
#

that starts your bot

oblique root
#

then i can have to bot just print the results?

oblique root
silk fulcrum
#

I dont get the problem

robust snow
#

If you pass the return of the random function into a message, something similar to

message.channel.send(f'{random_function_return}')

silk fulcrum
#

Do you just want a command?

robust snow
oblique root
#

i'm using pycharm and i have never made anything outside of the main.py, are you saying that both can operate in the same? i'm not great at the terms, i am very new to this and just trying to help out a group i moderate for haha

robust snow
#

Yes

oblique root
#

thank you!

robust snow
#

Within your main.py you can declare multiple functions that do different things

oblique root
#

i dont know why i thought that would not work

#

i am really new to the bot stuff, had messed with kivy before and when i would try to add certain things in, it would mess it up, so i assumed the same.

robust snow
#

declare a function like
async def random_generator():
-> do some things here
return something

and call it within the script using random_generator()

silk fulcrum
#

await then

cold tide
#

Function that deletes a bots message?

silk fulcrum
#

I did not understand that conversation, but ok

silk fulcrum
robust snow
unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
cold tide
robust snow
#

Sweet