#discord-bots

1 messages · Page 357 of 1

obsidian hill
#

wthhhh

autumn sierra
#

i tried making my bot send msg for join and leave with else msg
but its not working
the bot isnt entering

#

`@client.command(pass_context=True)
async def join(ctx):
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
await ctx.send("i have joined your party")
else:
await ctx.send("are you dumb? you need to join a voice channel first")

@client.command(pass_context=True)
async def leave(ctx):
if ctx.voice_client:
await ctx.guild.voice_client.disconnect()
await ctx.send("i am leaving the party guys")
else:
await ctx.send("hey dumbass, add me in a voice channel first")`

obsidian hill
#

this when I use sys right??

obsidian hill
autumn sierra
autumn sierra
obsidian hill
#

what?

viscid hornet
viscid hornet
#

dw about it, it happens

#

oh wait nvm, i thought he was talking to you and saying that was the solution

#

it literally says “pycache” as the folder name. what do you think the folder is for?

viscid hornet
autumn sierra
viscid hornet
autumn sierra
viscid hornet
unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

autumn sierra
#

i just copied the code frm my old prjct and pasted

#

then what happnd idk
but the bot used to do it in my old prjct

viscid hornet
meager rock
#

you're probably missing message_content intents. also that code is outdated.

autumn sierra
viscid hornet
viscid hornet
unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

autumn sierra
meager rock
viscid hornet
#

yes thats how imports work

obsidian hill
#

I still need help doin this 😂

viscid hornet
viscid hornet
#

stop saying def. say function or method if its inside a class

obsidian hill
#

I did ```py
from ..main import main

and got ```    from ..main import main
ImportError: attempted relative import with no known parent package```
viscid hornet
#

ask the person who gave you that answer

#

i couldnt tell you ngl

obsidian hill
#

didnt you tell me to do that? 😅

viscid hornet
obsidian hill
#

Idk who did

#

I think someone suggested sys but It didnt work

#

or I didnt do it right

viscid hornet
#

i said if you’re looking at proj root (like on the side where it says the parent folder name), you would do “from proj root.main import main”

obsidian hill
#

well idk what else to do then

viscid hornet
#

<prefix>ping

#

not even close

#

its a function arg

#

yes because you need to use your bot prefix

#

whats the prefix for your bot?

#

so replace “<prefix>” with “!”

#

yes, obviously

#

opens fine

#

why are you looking at images??

hushed galleon
viscid hornet
#

can you rephrase?

#

@blazing beacon

#

how long did it take you to realise you replace “<prefix>” with your prefix in “<prefix>ping”?

#

@vapid parcel look at this shit kekw

#

user

#

yes because you do <prefix><command>

#

so !help

#

help is the name and ! is the prefix

#

just make commands that do stuff

#

i feel like you should be learning python

#

!res

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

viscid hornet
#

learn python first ☝️

#

@vapid parcel come here rn and see this

#

stop saying def. say function or method if its in a class. be clear. this is like the fourth time i’ve told you this

#

its the fourth time i’ve said it and you’ve blown me off. just take my advice - you’re the one asking for help after all

hushed galleon
viscid hornet
#

do you read what i write?

#

where are you getting this from?

viscid hornet
#

then you should’ve heeded my advice long ago

#

waitwhat rephrase

#

you can set the name of the command to be that, but that’s not advisable at all

#

then you cant run any commands

hushed galleon
#

on_message would be necessary for this

viscid hornet
#

i cant tell if you want slash commands or not

viscid hornet
hushed galleon
# viscid hornet he said prefix call tho?

i dont think they strictly meant how would it be done via the commands extension, just how can it be done at all

(dpy can definitely handle responding to a bare slash)

#

the nice part of separating prefixes from the command name is that it's easier to change the prefix, like having a different prefix per guild as set by admin, or having multiple prefixes work for the same command

#

the design decisions were made like nearly a decade ago, when discord's slash commands didnt exist and there weren't dedicated bot accounts

viscid hornet
#

whos “he” kekeh

#

oh danny

#

mf went through a whole story arc 😭 @blazing beacon @vapid parcel

hushed galleon
viscid hornet
#

i dont wanna load 200 prefixes 😭🙏🏽

hushed galleon
blazing beacon
#

skidded from a tutorial ofc

hushed galleon
hushed galleon
# viscid hornet which one is better / easier?
async def get_prefix(bot, message):
    return something_from_db

bot = commands.Bot(command_prefix=get_prefix, ...)``` ```py
class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="not needed", ...)

    async def get_prefix(self, message):
        return something_from_db```
#

oh, like to suggest stuff to the library? sure, discussions would be fine for help-related things while issues would be suited for bug reports or feature requests

#

no those were just examples for dynamic prefixes

#

if you want something custom that doesn't look like <prefix><command>, on_message would be more suitable

#

you can still write commands at the same time if your on_message in a listener

#
bot = commands.Bot(...)

@bot.command()
async def add(ctx, x: int, y: int):
    await ctx.send(f"{x} plus {y} is {x + y}.")

@bot.listen()
async def on_message(message):
    if message.content == "!":
        await message.channel.send("Hello! I'm a cool bot!")```
#

kind of, some of dpy's decorators will look at the function name

#

in the case of command() and listen(), they have a parameter to let you specify the name separately from the function's name

hushed galleon
#

all function objects have a __name__ attribute which i assume discord.py uses if you don't provide a name in the decorator call ```py

def foo(): ...
foo.name
'foo'```

strong saddle
#

anyone know how to fix this?

hushed galleon
#

just dpy

viscid hornet
#

thats a keyword argument, so you assign something specifically to that. you can also have positional arguments, which are listed in order

hushed galleon
viscid hornet
#

say i have two servers, one is assigned “!” only for their server and the other has “?” assigned only for their server. how do i run commands using the two for both servers?

#

i’ll just make 10 bot instances, each with different command prefixes trollface

hushed galleon
viscid hornet
#

what do you want them for

viscid hornet
#

yes. you can (pretty much) make any table in sql

#

why would you want to do that when discord has already done it for you

#

!vps

#

._.

#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

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

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

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

hushed galleon
viscid hornet
#

why would you want to make your own? just call the API for chat history

viscid hornet
loud sierra
#

can someone pls help with render

render uses python 3.11.9 and its having a problem with wheel in requirements.txt

#

i downgraded to 0.37.1 still got same error (in wheel)

viscid hornet
#

why make your own db when you can just get the data from discord

loud sierra
#

"note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error"

loud sierra
#

okay

hushed galleon
#

hosting requires hardware, internet service, and electricity, so reputable services like digitalocean will charge you upfront to help pay the cost of running their business

hushed galleon
viscid hornet
viscid hornet
#

gas

#

lowkey need to sleep

viscid hornet
#

2 ways:

  1. check in a custom deco
  2. check inside the function
#

dont watch videos

#

they lead you astray

#

take it from me

#

im going to bed

#

fuck my life pain

blissful grove
#

How can I get the supports commands badge for my discord bot? It uses slash commands but there still seems to be no badge

robust fulcrum
#

I think you need to invite bot with application commands option checked?

coral ermine
#

you need to use this ```py
@bot.tree.command(name="your_command_name", description="Your command description")
async def your_command(interaction: discord.Interaction):
# Your command logic here
await interaction.response.send_message("Command executed!")

#

the discription is what shows up in the slash menu

#

like this bot i made like ask would be the command name and "Ask me anything" will be the command discription]

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @rancid citrus until <t:1714094349:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

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

coral ermine
#
import discord

# Replace with the actual channel name (case-sensitive)
channel_name = "your_channel_name"

intents = discord.Intents.default()
intents.message_content = True  # Needed for slash commands

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

@bot.event
async def on_ready():
    guild = bot.get_guild(guild_id)  # Replace with your guild ID if needed
    for channel in guild.text_channels:
        if channel.name == channel_name:
            target_channel = channel
            break
    else:
        print(f"Channel '{channel_name}' not found.")
        return

    # Use target_channel.send(...) to send messages

bot.run('your_bot_token')
golden portal
#

depends on what you're trying to do, may elaborate on it

coral ermine
#
@bot.event
async def on_message(message):
    if message.author == bot.user:  # Ignore bot's own messages
        return

    # Get the channel where the message was sent
    channel = message.channel

    # Get the member object representing the user who sent the message
    member = message.author

    # Check if the user is the server owner
    if member == message.guild.owner:
        print(f"{member.name} is the server owner.")

    # Check if the user has the "Administrator" permission
    if member.guild_permissions.administrator:
        print(f"{member.name} has administrator permissions.")
#

point 3

#

without the bot you can just right click the user ans see the user id

#

bro put all your concerns in one message up im unable to keep up😂😂😂

quick gust
#

No u can't

coral ermine
#

U cant unless its your own message

#

no it will come in the channel the best you can do is make the bot delete it as soon as the message shows up

#

what exactly are you planning on?

#

Check discord.py api docs it will have everyting that can be done

#

no its the user id of the user who wrote the triger message

#

This will send "hello" in the channel with that channel id

#

okay

#

guild means server

#

yes

#

server has many categories and catetories have many channels

#

example: this server/guild is called python in that we are in the "topical chat" category and this is the discord-bots text channel

#

yes there are many kinds of channels

#

this is a text channel

#

there is voice channel and threads

#

can i see your bots code im finding it difficult to understand wo it

blissful grove
#
 
from commands.plzhelp import plzhelp


class PersistentViewBot(commands.Bot):
    def __int__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix="/", intents=intents)

    async def setup_hook(self) -> None:
        self.add_view(ClaimTicketButtonView(timeout=None))
        self.add_view(UnclaimTicketButtonView(timeout=None))


bot = PersistentViewBot(command_prefix="/", intents=discord.Intents.all())

This is my initializer 👆

and then one of the slash commands /plzhelp


@bot.tree.command(name="plzhelp", guild=GUILD, description="View a list of commands")
async def plzhelp_command(interaction: discord.Interaction):  # Help Command
    await plzhelp(interaction,
                  allowed_role_ids=allowed_role_ids,
                  command_logs_channel_id=command_logs_channel_id,
                  bot=bot)
coral ermine
blissful grove
obsidian hill
#

In this cmd

if message.content.startswith('$test'):
        await message.reply('This is a test', mention_author=True)

How could I make it run a function then send the message?

turbid condor
obsidian hill
#

Ok thats what I did but got a weird error so Js making sure I did it right

turbid condor
#

so we can point out the mistake

obsidian hill
#

Its regarding a whole seperate thing, nothing to do with discord but ill send it

turbid condor
obsidian hill
#

what? 💀

#

anyways here python if message.content.startswith('$gen'): gen() await message.reply('Video Generation has started, please ensure your Direct Messages are public so our bot can send you your result.', mention_author=True) this the cmd

this the error

  File "C:\Users\liama\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\liama\Downloads\RedGen Files\Generator\bot.py", line 57, in on_message
    gen()
  File "C:\Users\liama\Downloads\RedGen Files\Generator\functions.py", line 31, in gen
  File "C:\Users\liama\Downloads\RedGen Files\Generator\reddit\subreddit.py", line 24, in get_subreddit_threads
    if settings.config["reddit"]["creds"]["2fa"]:
TypeError: There are no type variables left in dict['reddit']
obsidian hill
turbid condor
#

well the error is telling you that the structure of your the dict from which you are accessing variables might differ

#

from what you are using

#

so you should check what the structure of the dict looks like

#

and then change your statement accordingly

obsidian hill
#

well it works in main.py no error, just when calling the function in bot.py it gives that

turbid condor
#

that's what the error says

obsidian hill
#

yea but idk what to do now

obsidian hill
turbid condor
#

well even I don't have any expericence with reddit and their api so can't help in this case

obsidian hill
#

Is it an issue with the reddit gen stuff?

turbid condor
#

yes

obsidian hill
#

damn. Bc the generation works just fine with main.py but the second I put the main func in a cmd it breaks

turbid condor
#

it occurs here File "C:\Users\liama\Downloads\RedGen Files\Generator\reddit\subreddit.py", line 24, in get_subreddit_threads if settings.config["reddit"]["creds"]["2fa"]:

#

well you can try creating a post in #1035199133436354600 and someone who knows about the issue might help

obsidian hill
#

Hm I might be able to remove that, thats for when I had my reddit 2fa on but now that I dont I can prob remove it

obsidian hill
turbid condor
#

i doubt that's the issue

obsidian hill
#

alr then idk 😂

#

I just dont understand how when I run main.py it runs the main() function, now Im running the main function in another file and its breaking

#

@turbid condor Is there a specific way I need to call the function?

#

Like await main() ???

#

idfk 😭

turbid condor
#

nope

obsidian hill
#

well shi

turbid condor
#

await is used for coroutines

obsidian hill
#

are you avaliable to vc? If you wouldnt mind I can screenshare and maybe you could better help me here

turbid condor
#

and this function you are using isn't a coro

#

well sry can't i'm also occupied with my stuff

obsidian hill
#

alr nw

obsidian hill
#

How do I dm a user a mp4?

#

me?

blazing beacon
#

oh crap

#

i forgot to reply to the message

obsidian hill
#

😂 ?

#

ah all good

blazing beacon
#

not you

#

a few slight corrections

@bot.listen('on_message')
async def message_listener(msg):
    if msg.content == "!":
        await msg.channel.send(...)

in any case i think you should consider using commands an example is something like this

@bot.command()
async def command_name(ctx, arg1=None, arg2=None):
    await ctx.send(...)
flint stirrup
#

General question: I'm writing my own bot from scratch, but I'm largely confused on why the docs & examples for discord.py don't really use a class that inherits from discord.bot
Essentially I want a bot that does actions when messages are sent, deleted, or edited, and has custom command support. The docs & examples all basically never use a discord.bot-inherited class, and yet they do show a lot of examples of using a class that inherits from commands.Cog

I'm just at a general loss as to how to structure the bot

golden portal
# flint stirrup General question: I'm writing my own bot from scratch, but I'm largely confused ...

inheriting from commands.Cog is because you wanna create a Cog class, that's required because you want the functionalities of a Cog class and it can load properly with bot.add_cog

while, you dont necessarily need to inherit the commands.Bot class, because rarely would you want to override methods or modify the functionality of a Bot class.

For instance, this inherits the commands.Bot because they want to use and override the Bot.setup_hook, it's a necessary step. But you dont really have to do it if you dont need it.

unkempt canyonBOT
#

examples/advanced_startup.py line 18

class CustomBot(commands.Bot):```
flint stirrup
#

Oh I see, so you'd only create this child class to explicitly replace the built-in class variables & methods, but otherwise there isn't any benefit to doing so

golden portal
#

yea, or if you want to add attributes or whatever, since the convenience of the bot instance is you have access to it in pretty much most scope in dpy

#

which act as a global variable

cinder remnant
#

!start

unkempt canyonBOT
#
Star / Wildcard imports

Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.

Example:

>>> from math import *
>>> sin(pi / 2)
1.0

This is discouraged, for various reasons:

Example:

>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2)  # uses sin from math rather than your custom sin
  • Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
  • Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
  • Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.

How should you import?

  • Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
  • Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)

Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]

[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python

cinder remnant
#

that worked? lol

#

!start discordbot

#

!start bot

upbeat otter
cinder remnant
vale wing
#

Mee6 💀

viscid hornet
cinder remnant
upbeat otter
#

💀

#

yes

vale wing
#

Yeah, it's equivalent to

return None
viscid hornet
vale wing
#

That's me 😎

#
Spoon(size="comically large").feed(User(python_knowledge_level=PythonKnowledgeLevel.noob))
#

Comically large is so large I can't even convert it to integer

#

float("inf") 😔

viscid hornet
#

the whole point of making a message listener is for you to rename the function while still keeping the same event

#

in .event, the name of the function has to be the event you're watching for

#

but in .listen(), you can add the name of the event in the brackets and then rename the function itself

#
@bot.listen('on_message')
async def my_very_cool_message_listener(message):
    pass```
#

it's an event

#

and yes its dpy built in

#

rephrase what

#

you lost me

#

i answered your question

#

events are only for dpy

#

no, they're unique to every channel

#

you need to check the server before the channel

#

there is a .fetch_channel() function, now that i think about it

#

theres too many

#

what city shuts off all the electricity at a certain time?? pithink

#

doesnt mean you need to turn off all the electricity

#

they're public info. your user ID is: 1231805530008457246

#

fair enough shrug

primal gust
#

hey guys can anyone hel p me?

#

im tryna think of what i can use to make this work

#

basically i need to read a line of text from the output, grab a specific line from that output, and then store that line into a variable to be used later on in the process

#
Confidence Threshold:
31

0%


100%

{
  "predictions": [
    {
      "x": 115.5,
      "y": 227,
      "width": 79,
      "height": 88,
      "confidence": 0.374,
      "class": "rotten",
      "points": [```

for example, this is an output. I need to find "confidence": 0.374 and store it into a variable to be used later
#

thing is, i have no clue how to do it in one execution

#

yes

#

the thing i sent is from roboflow

#

im using machine image learning and i need to figure out how to store its results

#

yep pretty much

#

lol im a highschooler and its for a class im taking

viscid hornet
primal gust
#

oh sorry.

viscid hornet
#

this is a discord bot help channel

viscid hornet
primal gust
#

that got me confused

#

are those libraries?

#

im not working with a database rn tho, that's supposed to be placed on RPI

#

raspberry pi

#

thanks man

#

have a good one

viscid hornet
#

not for here ❌

#

channel literally says discord bots, not ML or AI

#

maybe. can this conversation move to #data-science-and-ml? definitely. should you go there to talk about this stuff? yes.

#

yes

#

this channel has an ID of: 343944376055103488

upbeat otter
#

yes the discord api works on ids only.

#

you have to invite the bot

#

otherwise imagine that random bots could be joining your server and nuking it

#

I mean if you're the server owner yes

#

or have admin permission

#

but you cannot make the bot join any random server. it has to be a server where you have the permissions to add a bot or you are the server owner

quick gust
#
Traceback (most recent call last):
  File "/home/ubuntu/Book-Verse/main.py", line 110, in <module>
    main()
  File "/home/ubuntu/Book-Verse/main.py", line 106, in main
    BookVerse().run()
  File "/home/ubuntu/Book-Verse/main.py", line 102, in run
    super().run(TOKEN)
  File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 1126, in run
    return future.result()
  File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 1105, in runner
    await self.start(*args, **kwargs)
  File "/home/ubuntu/Book-Verse/main.py", line 99, in start
    await super().start(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 1067, in start
    await self.connect(
  File "/usr/local/lib/python3.10/dist-packages/disnake/shard.py", line 501, in connect
    raise item.error
  File "/usr/local/lib/python3.10/dist-packages/disnake/shard.py", line 164, in worker
    await self.ws.poll_event()
  File "/usr/local/lib/python3.10/dist-packages/disnake/gateway.py", line 709, in poll_event
    raise msg.data
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/client_ws.py", line 244, in receive
    msg = await self._reader.read()
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/streams.py", line 681, in read
    return await super().read()
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/streams.py", line 640, in read
    await self._waiter
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/http_websocket.py", line 314, in feed_data
    return self._feed_data(data)
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/http_websocket.py", line 321, in _feed_data
    for fin, opcode, payload, compressed in self.parse_frame(data):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/http_websocket.py", line 486, in parse_frame
    raise WebSocketError(
aiohttp.http_websocket.WebSocketError: Received fragmented control frame```

what causes this?
upbeat otter
#

do you want to keep the memos separate for every server or do you wanna make it common

viscid hornet
#

they will never do that

upbeat otter
upbeat otter
viscid hornet
#

in each server:

  1. each person uses their own memo channel
  2. each person uses the same memo channel
upbeat otter
#

how did you actually understand what he was asking😭

#

why don't you use a database then

viscid hornet
viscid hornet
viscid hornet
viscid hornet
#

bot need db always store channel history read message read channel history. no db test channel db, bad not good

upbeat otter
#

it's not as efficient. you'll probably rate-limit yourself

RATELIMITING
If your bot makes too many requests to the discord API, then discord will temporarily (for some time) ban your IP address from accessing the API.

Every history fetch will make many requests to the API.
Then you will have to filter all those messages later which is a very tedious (hard and unnecessary) job.
Also, this will make your bot very slow until your IP gets banned.

#
if message.author.bot:
    #This means sender is a bot```
viscid hornet
#

no use db channel. bad practice ❌

#

use db. we no use channel db it only db no channel db or db channel

#

api call more expensive than cache call. they is use cache call which get info from memory. too many api call go bankrupt

viscid hornet
upbeat otter
#

good

#

use sqlite3

#

or an online noSQL db

viscid hornet
#

#

wrong link nvm

#

library

#

!d sqlite3 | but learn this first

unkempt canyonBOT
#

Source code: Lib/sqlite3/

SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.

The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.

This document includes four main sections:

viscid hornet
#

postgres?

#

dont bother prettythumbsup

#

start sqlite

upbeat otter
viscid hornet
#

no elephant. sqlite

viscid hornet
#

!ot

unkempt canyonBOT
viscid hornet
#

this guys tweaking @upbeat otter

upbeat otter
viscid hornet
upbeat otter
#

but ok

viscid hornet
viscid hornet
upbeat otter
upbeat otter
viscid hornet
viscid hornet
viscid hornet
#

!ot

unkempt canyonBOT
turbid condor
#

You should have ran and hosted it in the dream too that way wouldn't have to worry after waking up

#

Imagination is a wild thing you could have imagined it all

viscid hornet
turbid condor
#

See imagination is wild

golden portal
#

abc refers to Abstract Base Class, it's an OOP concept that defines common attr/methods that are inherited by multiple different classes. but it's not meant to be used directly, Messageable is an abstract class. Usable classes like DMChannel, TextChannel, etc inherits Messageable class

#

i kinda make it in simple terms but you get the idea

tawdry vector
#
import discord
from discord.ext import commands
import bot_token
import details



intents = discord.Intents.all()

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

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



@bot.event
async def setup_hook(): 
  cmd = await bot.tree.sync()
  print(f"loaded {len(cmd)} commands")



@bot.event
async def on_message(message):
  if message.author.id == details.my_id and "You received 35 Pokécoins!" in message.content:
    await message.add_reaction(details.new_mon)


@bot.command()
async def hello(ctx):
  await ctx.send("hello")

bot.run(bot_token.TOKEN)``` Guys my !hello doesn't work
#

@viscid hornet

#

I've seen u helping a lot of ppl can you help me too sorry for the ping

#

The on_message works here but not !hello

viscid hornet
tawdry vector
#

.

quick gust
#

you need to add await bot.process_commands(message) at the end of your event, outside the if condition

#

or you can change @bot.event to @bot.listen()

obsidian hill
#

How do I stop this discord timeout thingy? WARNING discord.gateway Shard ID None heartbeat blocked for more than 60 seconds.

quick gust
#

are you using any blocking module?

#

!blocking

unkempt canyonBOT
#
Asynchronous programming

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

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

import discord

# Bunch of bot code

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

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

async libraries

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

wait no nevermind, nothing in the command is awaited

#

How can I detect when a message is sent if the id of the channel is ...

young dagger
#

!pastebin

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

obsidian hill
#

I alr did it

#

it was simple fix

young dagger
obsidian hill
#

Like I said ive already figure it out. thanks

viscid hornet
#

!code | just to lyk

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

viscid hornet
#

and your issue is that when a message is sent in a DM, there is no guild, so .guild returns None

#

and None doesn't have any attributes, so None.id isnt a real thing

#

and therefore it raises errors

viscid hornet
#

use your own pc

#

just use a .env file or read it from a .txt file

#

i use a txt file since it doesnt add to the imports

#

encryption in this case doesnt really mean anything. just dont share your token directly and you have nothing to worry about

upbeat otter
#

format your code like this
```py

your code here

sick birch
#

no, putting your token in .env doesn't "encrypt" it

#

the reason we put secrets in .envs is because it's usually .gitignored, so it doesn't get pushed to version control, and also, when developing, you can view all your secrets in one place easily.

#

but the most important reason to use environment variables is to be 12FA: avoid putting configuration in code (and by extension, secrets) so you can deploy the same code in multiple environments with only configuration changes

#

just good practice stuff

viscid hornet
#

i said “or” for a reason

#

do either

#
if not message.guild:
    ...```
#

!code | also use syntax highlighting

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

viscid hornet
#

there is a way to check directly

#

just showed you

tawdry vector
#

Its fixed ty tho

viscid hornet
#

ohh alr then prettythumbsup

viscid hornet
#

.author.bot (bool)

#

its .author, not auther

flint stirrup
#

Can someone give me a high-level explanation on the differences between discord.Client and discord.ext.commands.bot ? I'm having trouble understanding when to use one over the other

viscid hornet
#

lemme get a list for you

flint stirrup
#

So most if not all the time I would be better off using bot over client

brazen raft
#

Maybe. It definitely leaves room to expand from

sick birch
echo dock
#

Who can help me i have got a problem the error is too long i cant send here come MP

limpid apex
#

Anyone know why this isn't editing the message?

import discord
from discord import ui, ButtonStyle, message
class editMessage(ui.Button):
  def __init__(self):
    super().__init__(
      label = "Edit message!",
      style = ButtonStyle.green,
    )

async def callback(self, interaction: ...):
  await interaction.response.edit(content = "Edited message")

#

This is bot.py code:

@bot.command(name="buttontest2")
async def buttontest2(ctx):
  button = buttons.editMessage()
  view = discord.ui.View()
  view.add_item(item=button)
  await ctx.send("Testing the edit function", view=view)
echo dock
limpid apex
#

Oh lol

viscid hornet
limpid apex
#

Thanks lmao

viscid hornet
echo dock
#

go mp pls

limpid apex
viscid hornet
#

!paste | put the error here

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

viscid hornet
echo dock
limpid apex
viscid hornet
viscid hornet
#

!code | also syntax highlighting 🗣️

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

viscid hornet
viscid hornet
echo dock
limpid apex
#

😭

viscid hornet
limpid apex
#

Line 5 man

echo dock
viscid hornet
limpid apex
#

Nono, thats his code

#

i was showing where traceback was

echo dock
#

And why is permission denied ?

limpid apex
#

🤷

brazen raft
#

Print the path you're trying to use and print the current working directory's path

#

See whether the path you're trying to use is in fact under the current working directory

#

I mean, I also have the suspicion that your cwd is C:\Windows\System32 because of the specific circumstance of using Python from MS Store

#

Either check whether the guild attribute gives None or the channel type is dm

upbeat otter
#

just ask the user if they are in dm Or not

#

auto bot? 💀like the transformers?

brazen raft
#

Private means it is a private dm (not a group, just with one user)

#

What

viscid hornet
#

just use whatever it returns to determine if its a dm or not

viscid hornet
limpid apex
#

I'm using replit it autosaves lol

viscid hornet
limpid apex
#

k

viscid hornet
brazen raft
#

If it equals "private" or discord.ChannelType.private

limpid apex
#

or anything really

viscid hornet
#

!d discord.ChannelType.private

unkempt canyonBOT
viscid hornet
#

show your code rn

brazen raft
#

@wide plaza You should refer to the documentations for things like this

limpid apex
viscid hornet
limpid apex
viscid hornet
#

your callback is outside of the class

limpid apex
#

OHHHH

#

im fuckin stupid lol

viscid hornet
limpid apex
#

🤷

#

Next question

#

can u edit embeds

viscid hornet
limpid apex
#

:D

viscid hornet
#

you can edit anything

limpid apex
#

yay

#

for editing an embed you would make a new one right?

viscid hornet
unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
limpid apex
#

and set content to the embed

#

k

viscid hornet
#

anything there can be edited

brazen raft
viscid hornet
viscid hornet
brazen raft
#

It's just a parameter

viscid hornet
#

ohhh

brazen raft
#

That function is probably never used in their program

viscid hornet
#

i see why it was saying there was no response

limpid apex
#

can I make multiple buttons in one class as well?

viscid hornet
limpid apex
#

k

#

what would 2 look like?

#

in code form, I mean

brazen raft
#

I think it fills rows of up to five

#

Oh

viscid hornet
limpid apex
#

Ty!

viscid hornet
# limpid apex Ty!

or ```py
class MyButton1(ui.Button):
...

class MyButton2(ui.Button):
...

class MyView(ui.View):
def init(self):
self.add_item(MyButton1())
self.add_item(MyButton2())```

limpid apex
#

I see

#

thank you

viscid hornet
#

i've used the second example for paginators because if there's only 1 page, you cant use attributes in the decorators so you cant set the last buttons to be disabled conditionally (if that makes sense)

limpid apex
#

I see

viscid hornet
#

so you cant do something like this ```py
class MyView(ui.View):
def init(self):
super().init()
self.my_var = 5

@ui.button(label = self.my_var, ...)
async def ...(...):
    ...
upbeat otter
#

😭

viscid hornet
#

you cant send commands in groups because bots dont take friend requests or interact with links

upbeat otter
viscid hornet
upbeat otter
#

well that's fine then but how tf do you work with OOPs then 😭

viscid hornet
#

also you're not comparing it to anything. you're most likely doing py print(discord.ChannelType.private)
and wondering why it doesn't magically make the comparison you want

upbeat otter
#

a bot will never join a group

viscid hornet
shrewd apex
upbeat otter
#

ok Asher is here 😳

upbeat otter
viscid hornet
#

3rd time py if message.guild: # something if in a server, None if in dm

shrewd apex
#

and u can still disable it inside the init no? checking length of pages

upbeat otter
#
if isinstance(message.channel.type, discord.ChannelType.private):
   #Message is in dm
shrewd apex
upbeat otter
shrewd apex
#

exams around the corner 😔

#

need to start studying (from tmrw)

upbeat otter
shrewd apex
#

yeah

upbeat otter
#

ic

viscid hornet
shrewd apex
#

i am pretty sure u can access it via self.button_decorated_method.disabled as well

#

!d discord.ui.button

unkempt canyonBOT
#

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

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

Note

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

so if there's only 1 page, it disables the buttons to move forward

shrewd apex
#

hmm no i was talking about accessing the button via its decorated method name instead of children

#
class A:
    def __init__(self):
        self.foo.disabled = True
    @discord.ui.button()
    async def foo(self, inter, button): ...
viscid hornet
#

no way its that easy

shrewd apex
#

i think it is? been a while since i have used dpy noe

viscid hornet
#

what the hell did you write 😭

shrewd apex
#

yeah their button decorator returns a button object

viscid hornet
shrewd apex
#

;-;

upbeat otter
upbeat otter
viscid hornet
upbeat otter
viscid hornet
shrewd apex
#

just cycle them back lol % time to bring out the modulo

upbeat otter
#

or just don't make pages

shrewd apex
#

spam embeds

upbeat otter
#

flood channels with long messages

#

yesss

tawdry vector
#

@viscid hornet

#

!embed

viscid hornet
tawdry vector
#

What's the command i forgot

#

I'm new

#

How to see embeds properties

viscid hornet
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
viscid hornet
#

check bot cmds

slate swan
#

@slate swan Long time no see

#

......

tawdry vector
#
embed = discord.Embed( description="Do not catch this Pokemon before the timer ends", colour="0x00ff00")
    await message.channel.send(embed= embed)```
brazen raft
#

Remove the quotation marks around the color value

#

Also I believe every embed must have a title but I'm not 100% sure

tawdry vector
slate swan
#

You just copy pasted the exact thing

brazen raft
#

"thing" is not so "exact"

tawdry vector
#

Pasted what?

slate swan
tawdry vector
#

Anyways my battery at one percent

#

Gn fellas

slate swan
tawdry vector
slate swan
#

?

tawdry vector
slate swan
#

Damn

slate swan
slate swan
#

yes

#

I thought u would ignore me

#

should have

#

Bruh

#

Anyway wht are u doing currently?

#

nothing

#

Do you know c#?

#

yes?

#

C sharp

#

i know what c# is

#

i had to learn it for school

#

U said "yes?" So i thought

slate swan
#

took me to what

#

To learn c sharp

#

. .....

#

idk i knew few languages before so it was pretty easy

#

i wouldnt take it as granted time to learn

slate swan
#

idk i had like 2h/week of c# lessons and it took 2months to learn all basics?

#

so about 16h

slate swan
slate swan
#

no not yet

slate swan
#

Last year?

#

yea

#

Good for ya..

vapid parcel
#

@viscid hornet if you don't need me for something important, do not fucking ping me to this server. It's really annoying when you ping me 3 times in a row for something I don't care abt.

#

Instead of making fun of someone for not understanding how to do something, maybe help them understand, instead of pinging me n making fun of them.

You could maybe not be a dick, and maybe HELP them and teach them something, sounds shocking.. but you should try it!! 😁

viscid hornet
vapid parcel
#

If you don't wanna help anymore, just move on, let someone else help.

#

Im sorry but its kinda annoying, we all start somewhere man.

noble estuary
#

yo is there a channel for people looking for jobs? looking for someone with experience in python (flask) and frontend development

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

noble estuary
#

oh damn 😭

viscid hornet
viscid hornet
vapid parcel
#

we have battle ship inside of discord 😭

viscid hornet
#

this mf learned pillow for battleships

#

make chess next 🤑

vapid parcel
#

already have

spice warren
viscid hornet
#

get it integ with discord

viscid hornet
viscid hornet
#
  1. no you wont be ratelimited because its a call to cache.
  2. you cant send a message with a custom id
  3. you get a message link through the context menu somewhere near replies. to format it, do: https://discord.com/channels/<guild_id>/<channel_id>/<message_id>
  4. you can check a message’s attachments through its attributes i think
Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

#

!d discord.Message.attachments

unkempt canyonBOT
viscid hornet
#

there you go

#

you can then check the file extension to see if its an image file

#

send a message with the same attachment or edit the message with a new attachment?

#

just get the attachment, store it as a variable and send a new message with said attachments

wide plaza
#

i will test it

viscid hornet
#

you need the ID to make the url so you already have it

warped cave
#

anyone know how i can make a command that sends multiple images and text ? i now use "file: file = discord.File". But i can only make it send 1 image that way

brazen raft
#

The files parameter exists

#

You can attach up to 10 files in one message though

warped cave
#

yeah but i dont know how it works, i now have this code for it:

bot.group()
async def viper_haven(ctx):
 
    file: File = discord.File(r'C:\Users\Luuk\Pictures\botniet.png', filename="bot.png")
    embed = discord.Embed()
    embed.set_image(url="attachment://bot.png")
    await ctx.send(embed=embed, file=file)```
brazen raft
#

It's a matter of doing more discord.File instantiations and passing them all as a list to the files parameter

viscid hornet
#

oh wait i forgot the bot is offline

#

there's a files kwarg that takes a list of File objects

#

so py await ctx.send(files = [File1, File2, File3])

warped cave
warped cave
#

ahhh okay, thank you

#

and the await ctx.send(embed=embed, file=file) should still be in the code

viscid hornet
slate swan
#

Bruh

viscid hornet
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

viscid hornet
#

we have this for a reason

#

87 more lines than what should be posted in here

warped cave
#

i now have this:

async def cypher_ascend_a(ctx):
  
  
    file: File = discord.File(r'C:\Users\Luuk\Downloads\cypher ascend-a one-way.png', filename="cypher ascend-a one-way.png")
    embed = discord.Embed()
    file: File = discord.File(r'C:\Users\Luuk\Downloads\cypher A site ascend.png', filename="cypher A site ascend.png")
    embed = discord.Embed()
    embed.set_image(url="attachment://cypher ascend-a one-way.png")
    embed.set_image(url="attachment://cypher A site ascend.png")
    await ctx.send('Aline yourself under this line in the generator and aim at the spike in the sky to get this heaven one-way')
    await ctx.send(files = [File1, File2, File3])
    await ctx.send(embed=embed, file=file)```
#

it doenst take the images on the await ctx.send(files = ['cypher ascend-a one-way.png','cypher A site ascend.png' ]) line

viscid hornet
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

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

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

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

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

Examples

Deleting bot’s messages...
viscid hornet
#

you do realise you could’ve just sent it as an actual link i can click on, right?

#

why do you have a bunch of “source_” variables at the top? you know you can just use whatever you’re assigning to them to skip the unnecessary extra step

#

an embed shouldnt matter

#

cleaner code >> working code

warped cave
viscid hornet
viscid hornet
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
warped cave
viscid hornet
#

(mods its a cat photo)

warped cave
#

ahhh

#

but i think im doing something wrong

viscid hornet
#

you can leave them blank, it doesnt change anything

viscid hornet
warped cave
#
async def cypher_ascend_a(ctx):

    class discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png", *, spoiler=..., description=None)
    file: File = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png")
    embed = discord.Embed()
    file: File = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher ascend-a one-way.png', filename="cypher A site ascend.png")
    embed = discord.Embed()
    embed.set_image(url="attachment://cypher ascend-a one-way.png")
    embed.set_image(url="attachment://cypher A site ascend.png")
    files
    await ctx.send('Aline yourself under this line in the generator and aim at the spike in the sky to get this heaven one-way')
    await ctx.send(files=['cypher ascend-a one-way.png', 'cypher A site ascend.png'])
    await ctx.send(embed=embed, file=file)```
#

i have this now but it says class discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png", *, spoiler=..., description=None) ^ SyntaxError: invalid syntax

viscid hornet
#

just put the filename in. the lib will handle the rest

#

and go from your parent folder using “/“ as a separator

slate swan
viscid hornet
warped cave
slate swan
viscid hornet
#

(the “./“ is optional)
“./ascend/A site/cyper A site ascend.png”

#

??

viscid hornet
warped cave
viscid hornet
viscid hornet
#

also make sure to learn commands

sick birch
#

we don't know how to build machines that think like humans yet pithink

pale zenith
#

Just get neuralink and use a real human clueless

sick birch
#

you need to learn how to do do machine learning stuff for this. it's outside the scope of this channel

#

easiest way is to just hook it up to chatgpt API

#

it is currently impossible to make machines think like humans

#

the best we can do is natural language models that pretend to talk like humans

viscid hornet
#

you are most definitely not going to make the first human intelligence AI model

sick birch
#

scientists with large data centers still have not cracked the problem

#

your best option is to either make your own language model and host it yourself, or use chatgpt's

#

most people just use chatgpt api

sick birch
#

not sure what you're saying

#

you can tell that to chatgpt too, it will pretend for you

#

only for the right purposes

viscid hornet
tawny hemlock
#
import discord


fp = "asset/image/image.png"

discord.File(fp)

with open(fp, "rb") as file:
    pngbytes = file.read()
    discord.File(pngbytes)

hello. i'm trying to create a File object from bytes, but this gives me an error. anyone know a fix?

File ~\.venv\Lib\site-packages\discord\file.py:97, in File.__init__(self, fp, filename, spoiler, description)
     95     self._owner = False
     96 else:
---> 97     self.fp = open(fp, 'rb')
     98     self._original_pos = 0
     99     self._owner = True

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
hushed galleon
tawny hemlock
#

thanks

turbid condor
#

I don't think ephemeral msg can be edited

latent pier
#

You sure?

turbid condor
#

Not sure

latent pier
#

I think i had seen it in some bot

turbid condor
#

But u can edit it via message.edit

latent pier
turbid condor
#

Since message is a Message object

latent pier
#

Or maybe I'm wrong

turbid condor
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
hushed galleon
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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

Edits the original interaction response message.

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

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

after using send_message(), the above method will be able to edit it

latent pier
#

I see

hushed galleon
#

and if you do need a message object, Interaction.original_response() is required to retrieve it since send_message() returns nothing

#

oh derp, forgot that wasnt allowed for ephemeral messages

latent pier
#

@turbid condor

turbid condor
#

If u are trying to edit the message with which button are attached then u can use edit_message instead of send_message

hushed galleon
#

wtf is with it showing (edited) 4 times

turbid condor
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

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

Responds to this interaction by editing the original message of a component or modal interaction.
latent pier
#

||not official client don't mind me|| @hushed galleon

turbid condor
#

But this can be only used for cases where working is similar to pagination

latent pier
turbid condor
#

What error it gave?

latent pier
#

I'm passing original 1st button's interaction into Pagination instance

hushed galleon
#

oh ya for a paginator, you'd have a fresh interaction with each button click, edit_message should be valid with that

latent pier
latent pier
#

Except stop button

#

All 4 buttons has same response

turbid condor
latent pier
turbid condor
#

Since an interaction can only be responded to once

#

Instead of await self.interaction... use await interaction.response.edit_message()

#

That should work

latent pier
#

I should try out this too

turbid condor
#

interaction.response.edit_message()

latent pier
#

Okay

turbid condor
#

I told u to recheck the message

latent pier
midnight oracle
#

Any idea why when I hosted my bot (for personal use) and I try to use any of the slash commands a This interaction failed error raises (in discord)? I have to say that, the commands are loaded correctly and the prefix commands work perfectly, the issue is only with the slash commands after the hosting.

coral ermine
#

Send the system logs

shrewd apex
#

defer the interaction

dusk ermine
#

Help

#

I don't understand the error since I make "/ciao".

turbid condor
#

the error??

slate swan
dusk ermine
slate swan
#

Did any exception raise?

#

Could you provide the code of ciao command?

shrewd apex
#

did you sync?

upbeat otter
#

why do people not even post their errors and expect help 💀

dusk ermine
#

@bot.tree.command(name='ciao', description='Says hello to a mentioned user.')
async def ciao(ctx: commands.Context, user: discord.Member):
await ctx.send(f"Ciao {user.display_name}!")

quick gust
#

3 people have asked u if it raised an error

turbid condor
dusk ermine
#

Oh

turbid condor
slate swan
#

main.py```py
import env,discord
from discord.ext import commands

intents = discord.Intents.all()

bot = commands.Bot(command_prefix='c!', intents=intents)

@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')

@bot.command()
async def ping(ctx):
await ctx.send('Pong!')

bot.run(env.DISCORD_API_TOKEN)```

how to arrange commands like ping into separate files inside a folder called 'commands' to avoid clutter in main.py

#

im trying

import env,discord,os
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='c!', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

async def load_extensions():
    for filename in os.listdir('./coms'):
        if filename.endswith('.py') and filename != '__init__.py':
            extension = f'commands.{filename[:-3]}'
            await bot.load_extension(extension)

bot.run(env.DISCORD_API_TOKEN)```
#

and inside the folder called coms i created ping.py and wrote this:

from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

def setup(bot):
    bot.add_cog(Ping(bot))
#

didn't work

#
2024-04-27 13:49:32 INFO     discord.client logging in using static token
2024-04-27 13:49:34 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: f1f239b070f2caaf9a2dbdd5016ed560).
Logged in as Catmium
2024-04-27 13:49:41 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found```
viscid hornet
viscid hornet
viscid hornet
slate swan
#

where do i write load_extensions()

viscid hornet
#

you need to call() it

slate swan
#

yes but where?

#

in main or in the command fiel?

viscid hornet
#

on_ready can be called multiple times so you dont wanna be reloading your extensions twice or thrice

slate swan
#

will this work?

viscid hornet
#

async functions are awaited

#

so “await my_func()”

slate swan
#

/home/cosmo/Documents/Catmium/main.py:16: RuntimeWarning: coroutine 'load_extensions' was never awaited
load_extensions()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

my bot is still running

viscid hornet
slate swan
viscid hornet
slate swan
#

yes you're texting before i'm done sending images lol

viscid hornet
slate swan
#

this?

#

@viscid hornet

#

bro what happened did you die

#

RIP bro 2024-2024

#

i miss my wife

viscid hornet
#

but remember the second thing

viscid hornet
slate swan
#
/home/cosmo/Documents/Catmium/main.py:19: RuntimeWarning: coroutine 'load_extensions' was never awaited
  load_extensions()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-04-27 14:07:50 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: f78bae503fe6f8d8cf89d8ca5c3035e8).
Logged in as Catmium```
slate swan
viscid hornet
#

try it again

bright dirge
#

I'm running into a problem with a quiz bot I'm making when it lasts more than 15 minutes. The entire game chains off the first interaction of calling the command to start it, but I've found out that the token of this interaction gets expired since all the commands begin to 401. I think a way around this would be setting a channel webhook instead, but I want it to be handled automatically by the bot. Is there a way to create channel webhooks via discord.py?

slate swan
#

@viscid hornet

#

mom

viscid hornet
#

thats whats raising the error

slate swan
#

no idea

#
import env,discord,os
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='c!', intents=intents)

async def load_extensions():
    for filename in os.listdir('./commands'):
        if filename.endswith('.py') and filename != '__init__.py':
            extension = f'commands.{filename[:-3]}'
            await bot.load_extension(extension)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.event
async def setup_hook():
    await load_extensions()

bot.run(env.DISCORD_API_TOKEN)
#
from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

def setup(bot):
    bot.add_cog(Ping(bot))
slate swan
viscid hornet
#

ah

viscid hornet
slate swan
viscid hornet
#

and the adding cog should be awaited

viscid hornet
#

that should be async

slate swan
#

im going to bathe can u rewrite it ples

#

oh async def setu(bot)?

viscid hornet
#

and then await your “add_cog”

slate swan
#

yay love you

#

it workeis

#

i lost my morals back in vietnam

viscid hornet
slate swan
viscid hornet
#

why

slate swan
#

what is your name?

viscid hornet
slate swan
#

ok axo ! your pokemon adventure is about to unfold! a world of dreams and adventures await!

viscid hornet
#

but if you have to know, its amelia

slate swan
#

na it's okay

viscid hornet
#

!ot kinda off topic now

unkempt canyonBOT
slate swan
#

uw

#

If my embed length crosses the limit of 6000 characters, when will the error raise, when I change for example the description and it crosses that limit or when I attempt to send the embed?

upbeat otter
#

I think

#

need to check the source code

#

or just try it

slate swan
#

I looked at the src and yeah, most likely it will error when I attempt sending it

#

the checks are preformed in interaction_message_response_params method

#

which is called when sending the message via response.send_message

#

this one is weird though

#

self refers to a ChannelSelect

slate swan
#

alright

#

thats a good info for me

viscid hornet
slate swan
#

😭 🙏

viscid hornet
slate swan
#

type ignore my beloved ducky_devil

viscid hornet
slate swan
#

its used to ignore type warnings from your typechecker

slate swan
#

@viscid hornet Apparently everything works

#

so that type warning/error was useless :kekw:

#

guys, gitignore isn't ignoring the pycache inside commands folde

#

try just __pycache__/ pithink

slate swan
#

weird

#

how about commands/__pycache__/

#

didn't work

#

k

viscid hornet
slate swan
#

fr

#

an exchange for better autocompletion 😭

upbeat otter
slate swan
upbeat otter
#

ok skill issue

slate swan
#

thats cursed

slate swan
viscid hornet
slate swan
viscid hornet
upbeat otter
#

I mean why does bro have to do that to gitignore 😭

slate swan
viscid hornet
#

i saw one posted here the other day

slate swan
#

holdup

upbeat otter
upbeat otter
#

nitro flex

viscid hornet
#

i’ll fix it later

viscid hornet
#

its expiring in 2 days

upbeat otter
slate swan
viscid hornet
viscid hornet
quick gust
# slate swan doesnt work

it doesn't show the "Untracked" sign, as it does "M", so I'm assuming you have already pushed it to github once. Now you cannot gitignore it. The solution would be to delete that folder (and add __pycache__ in gitignore)

shrewd apex
#

u can remove it from staging tho

#

git reset HEAD -- path/to/file

quick gust
#

thank you for the info! I didn't know this

ivory falcon
#

how to add choices to a slash command?

viscid hornet
viscid hornet
# viscid hornet you can either use a literal typehint, typehint to an enum or add choices in a d...

Want users to select something from a hard coded list?
Use "choices", three different ways to do it. Need channels, roles, members, etc? See ?tag slash types.
View Documentation (has examples)

Option 0: True & False
Need True and False as choices? Simply type the argument with bool and discord will handle it.```py
@...command(...)
async def testephemeral(
interaction: Interaction,
ephemeral: bool
):
print(ephemeral, type(ephemeral))

will print either True or False

**Option 1: typing.Literal**
This is the easiest.```py
from typing import Literal
 
@...command(...)
async def choosecolour(
  interaction: Interaction,
  colour: Literal["Red", "Green", "Blue"]
):
  print(colour) # will print either "Red", "Green" or "Blue"

Option 2: @app_commands.choices```py
from discord import app_commands

@...command(...)

name is shown to the user and value is returned to you.

value can be of type str, int or float.

@app_commands.choices(
colour=[ # param name
app_commands.Choice(name="Red", value="red"),
app_commands.Choice(name="Green", value="green"),
app_commands.Choice(name="Blue", value="blue")
]
)
async def choosecolour(
interaction: Interaction,
colour: Choice[str] # [str] denotes the value type, not required.
):
print(colour) # will print the chosen Choice obj

colour.name for the name and colour.value for the value you set

**Option 3: enum**```py
from enum import Enum

class Colours(Enum):
  # format: name - value
  Red = "red"
  Green = "green"
  Blue = "blue"

@...command(...)
async def choosecolour(
  interaction: Interaction,
  colour: Colours
):
  print(colour) # will print our enum. in this case, the Colour class above
  # colour.name for the name and colour.value for the value you set

Options 0, 1 and 3 also work for hybrid commands.
Choice obj cannot be set as default.

viscid hornet
ivory falcon
# viscid hornet **Want users to select something from a hard coded list?** Use "choices", three ...

i've tried the second one and it worked! but then i checked the terminal and there was this;

  interaction.response.send_message("test")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback``` 
 
code:
 
```@tree.command(
    name="welcome",
    description="Enable welcoming for new user"
)
@app_commands.choices(
    active=[
        app_commands.Choice(name="on", value="on"),
        app_commands.Choice(name="off", value="off")
    ]
) 
async def welcome(interaction: discord.Interaction, active: app_commands.Choice[str]):
    interaction.response.send_message("test")```
shrewd apex
ivory falcon
#

OH

#

now i noticed

celest cliff
#

hi guys, is there any good guide on learning to make discord bots in python? i can already program in python

celest cliff
#

ty

slate swan
#

Hello could someone help please I am trying to build a discord bot with interactive buttons but I keep getting errors even after installing pip discord-components.

  File "/home/container/main.py", line 3, in <module>
    from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
ModuleNotFoundError: No module named 'discord_components'
customer@apollopanel~ Server marked as offline...
[Pterodactyl Daemon]: ---------- Detected server process in a crashed state! ----------
[Pterodactyl Daemon]: Exit code: 1
[Pterodactyl Daemon]: Out of memory: false
[Pterodactyl Daemon]: Aborting automatic restart, last crash occurred less than 60 seconds ago.```
turbid condor
little urchin
#

Could anyone help with this issue
import discord

intents = discord.Intents.all()
intents.typing = False
intents.presences = False

client = discord.Client(intents=intents)
token = ''

@client.event
async def on_ready():
print(f'Logged in as {client.user.name} ({client.user.id})')

@client.event
async def on_message(message):
print (f'Message from {message.author}: {message.content}')

client.run(token)
I want it as a message logger but when I open it it closes immediately

slate swan
#

why do you want to log messages of others?

viscid hornet
viscid hornet
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

little urchin
viscid hornet
#

wrong way around

little urchin
little urchin
#

And put encryption

viscid hornet
little urchin
#

No I have a seperate sxript

#

For sendingessages

#

With webhook

little urchin
viscid hornet
#

this sounds a little extra if ima be honest

little urchin
#

Idk why

viscid hornet
unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

viscid hornet
#

also you should be running this inside of a code editor since if you run it by double clicking it, it’ll close down automatically if theres any errors

little urchin
#

I know

#

I did it inside vscode