#discord-bots

1 messages Β· Page 1093 of 1

fading marlin
#

again, it's not a json, it's a list of dictionaries

flint isle
fading marlin
#

iterate through the list, and grab the text keys

#

this is getting kinda off-topic for this channel, consider using a more appropriate channel maybe?

flint isle
fading marlin
#

do you know how to make a for loop?

flint isle
fading marlin
#

then you know how to iterate through a list rooDuck

flint isle
#

ok lol thanks

slate swan
#
me = client.get_user(id)

This returned a NoneType object instead of a member object

#

also the Id I used was my user id

#

the method is a cache lookup which can return None

#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
slate swan
#

you can make an api request, but i recommend you check first in cache and then make the call

#

Alright, ty

#

!d discord.ext.commands.Bot.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
slate swan
#

is the method that calls the api

heavy folio
#

im making a calculator command (usage: .calc 1k+9.5m) but i need help replacing stuff like 1k to 1000 and 9.5m to 9500000
do i need regex for this and still cant find any lib for safe calculating (some people said to use eval() but i doubt thats safe)

pulsar bay
#

what lang is fastest for discord bots

shrewd apex
shrewd apex
heavy folio
#

last sentence

supple thorn
#

You’d just have to find every number with a letter next to it and have a dictionary with the values of the letter and multiply the number with of the letter’s corresponding value

slate swan
#

its not like discord will respond faster to javascript and slower to rust

maiden fable
#

Dudes at what time do y'all even wake up 😐

maiden fable
#

Lmao imagine if I sleep at 3 and wake at 6

#

Hella difficult

shrewd apex
#

btw i tried the imgur api hunter

#

it was too slow tho like 2-4 secs for a req

karmic marsh
#

yall, what libraries are you using?

shrewd apex
karmic marsh
#

I'm trying disnake currently and it seems relatively intuitive

shrewd apex
#

people here use dpy2.0/hikari/disnake/few use pycord and nextcord

short silo
#

something: Option(choice=[1, 2, 3], description="something") isnt this how you give choices, choices arent showing up though

karmic marsh
#

I'm still trying to figure out how cogs work

short silo
karmic marsh
#

I've got them working for slash commands but I don't know how to use them for other sorts of interactions

slate swan
slate swan
#

nobody uses py-cord really

shrewd apex
#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
short silo
#

so, uh, we have to create multiple of these instead of passing a list ?

shrewd apex
#

no u pass these in the list

slate swan
#

Im trying to use cogs for the first time, and my file structure looks like this

short silo
#

hmm, what if i wanted to give the user a list of guild channels to choose from

slate swan
#

why

#

Can I not do that?

karmic marsh
#

don't have .py

slate swan
#

^

karmic marsh
#

'cogs.events.CommandEvents'

slate swan
#

so should I use [:-3] to remove .py

paper sluice
#

ya

slate swan
karmic marsh
#

literally where you have bot.load_extension("cogs.events.CommandEvents.py") in your code replace it with bot.load_extension("cogs.events.CommandEvents")

paper sluice
#

imagine manual loading

slate swan
#

im not manual loading

karmic marsh
#

I don't have a clue what I'm doing lmao

slate swan
#

I just haven't used cogs

slate swan
#

thats my code

im getting this now

discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.events.__pycach' could not be loaded.

rare saddle
#

How to find author through thread? MongoDB -> I have a branch and I need to search MongoDB to find the author of this branch

slate swan
unkempt canyonBOT
#

property text_channels```
A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.
paper sluice
#

or just use pathlib

slate swan
#

cool

#

ill check that out rn, thanks one sec

slate swan
slate swan
paper sluice
#

~~```py
for file in pathlib.Path(path-to-cogs-dir).glob('**/*.py'):
bot.load_extension(file[:-3])

short silo
paper sluice
slate swan
#

bro ryuga thats sus

paper sluice
#

😳 os.listdir bad

slate swan
#

discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.events.__pycache__' has no 'setup' function.

#

.... 😦

#

check if the file starts with an underscore

karmic marsh
#

oops, didn't mean for that to be a reply but oh well

#

that does the trick

slate swan
rare saddle
#

How to find author through thread? MongoDB -> I have a branch and I need to search MongoDB to find the author of this branch

slate swan
#

thats what the folder looks like. im pulling CommandEvents

karmic marsh
short silo
slate swan
#

which returns a module object

karmic marsh
#

no clue what that means lmao

slate swan
#

!e

print(__import__("random").randint(1, 10))
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

5
slate swan
#

i forget that isnt like range smh

karmic marsh
#
for cog in __import__("pathlib").Path('cogs').glob('*.py'):
    bot.load_extension(f'cogs.{cog.stem}')
karmic marsh
#

but why

slate swan
#

would deny on that

slate swan
#

W W W W, I got it. Thanks guys

short silo
slate swan
#

gave up on using cogs like 6 months ago but I finally got it

slate swan
#

are cogs all that beneficial?

paper sluice
umbral oriole
#

hello guys

#

Guys do you know who is@vocal snow ?

slate swan
#

yes

umbral oriole
#

Oh please could you introduce me

paper sluice
#

😳 u ping = u talk

slate swan
#

yup

#

just ping him in an ot channel lol

umbral oriole
#

alright bro thank you bro

karmic marsh
#

what can you put in a cog?

#

for example, can I put on_ready stuff in a cog?

#

if so, how?

slate swan
paper sluice
slate swan
slate swan
paper sluice
#

😭 .

karmic marsh
#

do yall care to elaborate or should I just try to figure it out?

slate swan
#

!d discord.ext.commands.Cog.listener

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

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

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

Example...
keen mural
#

how do i make a button view time out after a certain amount of time

#

timeout=None makes it never timeout but subbing in a number makes it time out instantly

slate swan
#

!d discord.ui.View.timeout

unkempt canyonBOT
#

property timeout```
The timeout in seconds from last interaction with the UI before no longer accepting input. If `None` then there is no timeout.
karmic marsh
#

cool well I still don't know what I'm doing but it's not erroring in VSC so that's a good start

slate swan
slate swan
keen mural
paper sluice
karmic marsh
#

okay well it doesn't work

paper sluice
keen mural
#

it times out instantly

paper sluice
#

wdym doesn't work? show code

karmic marsh
#

uhh

#

not sure I want to

keen mural
#
class Fight3(discord.ui.View):
    def __init__(self, context: commands.Context):
        super().__init__(timeout=4)```
karmic marsh
#

it's hideous

keen mural
#

Β―_(ツ)_/Β―

keen mural
#

ok

karmic marsh
#

want to share a working example?

paper sluice
slate swan
#

what do you expect ofc it will timeout😭

keen mural
#

is the problem (no matter what time)

paper sluice
#

u sure ur using Fight3 view?

keen mural
#

yes

karmic marsh
paper sluice
slate swan
keen mural
#

because wait for the view and the else statement triggers instantly and the button doesnt work

paper sluice
#

ur subclassing view and using wait_for? why 😭

karmic marsh
#

holy, okay

#

well this works, somehow

keen mural
#

why is await view3.wait() bad

karmic marsh
#

care to tell me everything that's wrong with it?

#
from disnake.ext import commands
from bot import SERVERID


class OnReady(commands.Cog):
    def __init__(self, bot: commands.Bot.listen):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'{self.bot.user.name} has connected to Discord!')
        print("The bot is ready!")
        guild = self.bot.get_guild(int(SERVERID))
        members = '\n - '.join([member.name for member in guild.members])
        print(
            f'{self.bot.user.name} is connected to the following guild:\n'
            f'{guild.name} (id: {guild.id})\n'
            f'Guild Members:\n - {members}'
        )


def setup(bot: commands.Bot.listen):
    bot.add_cog(OnReady(bot))
paper sluice
# keen mural why is await view3.wait() bad

just do

class Fight3(discord.ui.View):
    def __init__(self, context: commands.Context):
        super().__init__(timeout=4)
    
    @discord.ui.button(...)
    async def callback_for_this_button(...):
        ...

just do this, why do u need wait_for ?

keen mural
#

im confused

slate swan
keen mural
#

in the main command its await view2.wait()

#

or view3 whatever

karmic marsh
paper sluice
keen mural
#

yes i do that

paper sluice
#

what do u want to do when someone clicks the button?

slate swan
slate swan
karmic marsh
#

oh uh yeah I have no clue what I'm doing there

keen mural
karmic marsh
#

but it does work

slate swan
#

does it get called?

karmic marsh
#
import pathlib
for cog in pathlib.Path('cogs').rglob('*.py'):
    bot.load_extension(f'cogs.{cog.stem}')
slate swan
#

Hey okimii πŸ‘‹

karmic marsh
#

pretty sure that calls it?

slate swan
slate swan
karmic marsh
#

I don't have a clue but this is the output when I run it:

PS C:\Users\carso\Documents\Discord Bots\Bot 2> & C:/Users/carso/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/carso/Documents/Discord Bots/Bot 2/bot.py"

Magic DisBot has connected to Discord!
The bot is ready!
Magic DisBot is connected to the following guild:
Simplex (id: 983259662411501578)
Guild Members:
 - Carson
 - CC
 - Magic DisBot
paper sluice
karmic marsh
#

so it seems to be working as intended, probably/maybe/I hope

paper sluice
#

whats wrong there?

karmic marsh
#

oh it was all horribly wrong but like I said, it seems to be working'

#

after I've fixed some stuff

slate swan
karmic marsh
#

oh? how so

keen mural
#

nvm.

karmic marsh
#

the first bit is the 'being run' part and the rest is the output, if that's what you mean

slate swan
#

!d discord.on_connect

unkempt canyonBOT
#

discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") for that.

The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") also apply.
karmic marsh
#

oh, I see

slate swan
#

would be the right function for that

#

on_ready is a library abstraction lol

karmic marsh
#

ah, I see

#

yeah, that makes sense

#

so then this should be good?

#
from disnake.ext import commands
from bot import SERVERID


class OnConnect(commands.Cog):
    def __init__(self, bot: commands.Bot.listen):
        self.bot = bot

    @commands.Cog.listener()
    async def on_connect(self):
        print(f'{self.bot.user.name} has connected to Discord!')
        print("The bot is ready!")
        guild = self.bot.get_guild(int(SERVERID))
        members = '\n - '.join([member.name for member in guild.members])
        print(
            f'{self.bot.user.name} is connected to the following guild:\n'
            f'{guild.name} (id: {guild.id})\n'
            f'Guild Members:\n - {members}'
        )


def setup(bot):
    bot.add_cog(OnConnect(bot))
slate swan
#

yes but now your second sentence isnt correct lmao

karmic marsh
#

gah

#

what did I do lmao

slate swan
#

the bot wont be ready and it wont ever print the guild members

#

your clients cache hasnt been set up yet so you would need to use Bot.wait_until_ready

karmic marsh
#

it does print the guild members

slate swan
slate swan
karmic marsh
karmic marsh
slate swan
#

!d discord.ext.commands.Bot.wait_until_ready

unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
slate swan
#

can be used

karmic marsh
#

now it doesn't work lmao

#

no wait

slate swan
#

πŸ‘οΈ

karmic marsh
#

yeah, it's not working now lol

slate swan
#

weird

karmic marsh
#

so is there a solution, or do I just use on_connect and forget about it?

slate swan
#

do whatever you like lol

karmic marsh
#

fair enough

#

oh, I do have one more question

#

I know that with Client it's possible to respond to messages without a prefix

#

is the same possible with Bot?

slate swan
#

with on_message? yeah

#

the Bot class is the subclass of Client so everything the Client has the Bot has aswell

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

I just don't know what I could do to get around the issue

slate swan
#

just use on_ready

karmic marsh
#

alright lol

#

okay... yikes

#

I'm definitely not ready to be messing around with modals lol

slate swan
#

you should try making them

#

πŸ˜”πŸ˜­

karmic marsh
#

I've already got the disnake tutorial one working

#

both the high-level and low-level implementation

#

as cogs no less

drifting arrow
#

Awesome! πŸ˜„

karmic marsh
#

I just should probably try to understand the basics before I move on to more complicated things lol

#

although tbf that's really not my style

slate swan
#

can anyone give me an example how to use
create_sticker()
with message.attachments

#

!d discord.Guild.create_sticker ( checking docs )

#

i have seen not sure what to add in file

karmic marsh
#

hmm... I don't know that I can add message-id to the modal's id in the high-level implementation

#

here's what the code looks like:

import disnake
from disnake.ext import commands
from disnake import TextInputStyle

class MyModal(disnake.ui.Modal):
    def __init__(self):
        # The details of the modal, and its components
        components = [
            disnake.ui.TextInput(
                label="Name",
                placeholder="Foo Tag",
                custom_id="name",
                style=TextInputStyle.short,
                max_length=50,
            ),
            disnake.ui.TextInput(
                label="Description",
                placeholder="Lorem ipsum dolor sit amet.",
                custom_id="description",
                style=TextInputStyle.paragraph,
            ),
        ]
        super().__init__(
            title="Create Tag",
            custom_id="create_tag", # the message ID needs to go here appended to the end
            components=components,
        )

    # The callback received when the user input is completed.
    async def callback(self, inter: disnake.ModalInteraction):
        embed = disnake.Embed(title="Tag Creation")
        for key, value in inter.text_values.items():
            embed.add_field(
                name=key.capitalize(),
                value=value[:1024],
                inline=False,
            )
        await inter.response.send_message(embed=embed)

# The command that creates the modal

class ModalHCommand(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command()
    async def taghigh(inter):
        """Sends a Modal to create a tag."""
        await inter.response.send_modal(modal=MyModal(inter))


def setup(bot):
    bot.add_cog(ModalHCommand(bot))
unkempt canyonBOT
#

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

Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") object.

New in version 1.1.
slate swan
#

this gives you the bytes data

#

you can use io.BytesIO to convert it into io.BufferedIOBase, and then pass it in discord.File to use it for the file kwarg

#

okay

maiden fable
#

Nothing to do anyways

slate swan
#

i just wrote what the docs say.

maiden fable
#

Nice

rare saddle
#

In mongoDB, how do I get the ticket author from this list?

slate swan
#

tickets[0].get('author') ig?

rare saddle
#

There may be many

slate swan
#

you want the author of all of them?

#

seems like a case of list comps

rare saddle
slate swan
#

basically, you have a thread id and you want the author id revalent to it, correct?

maiden fable
#

Best thing. Use json.dumps and send the string form of dict to the MongoDB

rare saddle
#

But I don't know how to implement it in mongoDB

maiden fable
#

What module u using?

rare saddle
maiden fable
#

For MongoDB

slate swan
#

i would just py thread = [ obj.get("author") for obj in tickets if obj.get("thread")== thread_id] pithink

rare saddle
slate swan
#

and use the 0th index if the list was not empty

maiden fable
slate swan
#

not sure if mongo provides some better internal ways

maiden fable
#

Used Mongo only once for HunAI and i am never using it again

rare saddle
#

inter.channel.id = thread.id

slate swan
#

thread there is a list.

slate swan
rare saddle
#

@slate swan

#

Sorry if I misunderstood something

slate swan
#

xcm_bruh can you try printing the tickets variable?

rare saddle
#

yea

#

one sec

rare saddle
slate swan
#

it would look like i would just ```py
thread = [ obj.get("author") for obj in tickets if obj.get("thread")== thread_id][0]

maiden fable
slate swan
#

but if the data for that channel is not there in the db, the list will be empty and you will get an IndexError

boreal ravine
rare saddle
#

In case it leaves the server, it's worth checking

slate swan
#

and it would return None if its not anyways pithink you can always check for it

rare saddle
#

thanks you so much

slate swan
#

pleasure, also make a check for the cases i and sift just mentioned ( the list being empty or if the author is missing ), tho its shouldnt happen since you save the data for each thread right?

boreal ravine
karmic marsh
#

I don't think it's hard, I just don't know how to do it

rare saddle
rare saddle
slate swan
slate swan
#

!e ```py
obj = { "apple" : 0 }
print(obj[0])

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | KeyError: 0
boreal ravine
slate swan
#

you see why^

boreal ravine
stiff gorge
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() got an unexpected keyword argument 'label'
      components = [
        [discord.Button(
        label='Next meme',
        style=discord.ButtonStyle.blurple,
        custom_id='next'),
         
         discord.Button(
           label='End interaction',
           style=discord.ButtonStyle.red, 
           custom_id='exit')]]
      
      message = await ctx.send(embed=meme_opt(), components=components)
      id=message.id
slate swan
#

yep

boreal ravine
rare saddle
slate swan
rare saddle
#

When creating a new ticket, all data is recorded in the same way

slate swan
#

do you get some errors or something?

rare saddle
slate swan
#

nothing in ur terminal?

rare saddle
#

But in another ticket - everything works

slate swan
#

your current code is checking the the tickets owned by the user who clicked the button, so you won't be able to see threads owned by others ( where author id is not ur id )

rare saddle
boreal ravine
slate swan
#

try asking the author registered with that thread to do that interaction, that should do...

karmic marsh
#

nah, I got it

karmic marsh
#

I wanted to add the user's ID so that the message would persist only for the user (or I could use the message ID and make it not persist at all)

rare saddle
slate swan
#

pWut pog

loud junco
#

πŸ’€

maiden fable
#

Hi there Hydro

#

How is yr bot minecraft going on?

unreal spire
#

how do you stop output from a cog (excluding errors) from being displayed in the console?

shrewd apex
#

wdym?

#

display in consoles happen only when u use a print statement generally

karmic marsh
#

Yeah ^

unreal spire
#

is there a way to hide the print statement from a cog without removing print()?

karmic marsh
#

What does that even mean?

#

print is a function that writes to the console. That's all that it does.

maiden fable
karmic marsh
#

If you want it to not write to the console, remove the print

#

Or if you want to see it but don't want it to run for whatever reason, comment it out

unreal spire
maiden fable
unreal spire
karmic marsh
#

Ah, I see. That still doesn't seem like the most effective method but it's about the only thing that makes sense lol

stiff gorge
#
ext/commands/core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'view' is not defined
              r=requests.get("https://meme-api.herokuapp.com/gimme")
              res=r.json()
              title=res["title"]
              ups=res["ups"]
              author=res["author"]
              link=res["postLink"]
              memes = discord.Embed(description=f"[{title}]({link})",colour=0x2f3136)
              memes.set_image(url=res["url"])
              memes.set_footer(text=f"πŸ‘ : {ups} ✍️ : {author}")
              return memes
              
              view = discord.ui.View()
              item1 = discord.ui.Button(
                label='Next meme',
                style=discord.ButtonStyle.blurple,
                custom_id='next')
      
              item2 = discord.ui.Button(
                label='End interaction',
                style=discord.ButtonStyle.red, 
                custom_id='exit')
      
      view.add_item(item1)
      view.add_item(item2)
      message = await ctx.send(embed=meme_opt(), view=view)
      id=message.id
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

how do i fix this error, when i run it on repl etc it works but not on desktop

maiden fable
#

don't use 3rd party libs

#

use a fork of dpy or dpy v2

slate swan
maiden fable
#

Meh

slate swan
slate swan
maiden fable
slate swan
slate swan
#

version 2

maiden fable
#

So i meant dpy v2

#

Just telling him the same thing- Use a fork or 2.0

slate swan
slate swan
#

lmao

maiden fable
maiden fable
#

Yea....?

#

Imagine misreading

slate swan
#

elaborate

maiden fable
#

Ah wait nvm

#

I meant either use fork of dpy or use dpy v2

stiff gorge
#
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: IndentationError: expected an indented block (image.py, line 462)
              id=message.id
              while True:
                try:
                interaction = await self.bot.wait_for(
                  'button_click',
                  check=lambda inter: inter.message.id == message.id,
                  timeout=30)
                
                except asyncio.TimeoutError:
                  for row in components:
                    row.disable_components()
                    return await message.edit(view=view)
                    
                    if(interaction.author.id==ctx.author.id):
                      if(interaction.custom_id=="next"):
                        await interaction.edit_origin(embed=meme_opt(),view=view)
                        elif(interaction.custom_id=="exit"):
                          for row in components:
                            row.disable_components()
                            message=await ctx.fetch_message(id)
                            return await interaction.edit_origin(embed=message.embeds[0],view=view)
                      else:
                        await interaction.send("Hey! This is not for you!")
slate swan
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

maiden fable
stiff gorge
#

yes i did leave space now

maiden fable
stiff gorge
maiden fable
#

weird u already have an indent if I ain't missing smth

slate swan
# stiff gorge
try:
interaction = ...``` 🚫 
```py
try: 
  interaction = ...``` βœ…
stiff gorge
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: SyntaxError: invalid syntax (image.py, line 472)
elif(interaction.custom_id=="exit"):

            except asyncio.TimeoutError:
              for row in components:
                row.disable_components()
                return await message.edit(view=view)
                if(interaction.author.id==ctx.author.id):
                  if(interaction.custom_id=="next"):
                    await interaction.edit_origin(embed=meme_opt(),view=view)
                    elif(interaction.custom_id=="exit"):
                      for row in components:
                        row.disable_components()
                        message=await ctx.fetch_message(id)
                        return await interaction.edit_origin(embed=message.embeds[0],view=view)
                  else:
                    await interaction.send("Hey! This is not for you!")
maiden fable
#

U have an extra indent

left idol
#

using pycord right now my command goes through and the button interaction works properly but it says the application did not respond?

await interaction.response.defer()
# bunch of stuff 
await interaction.message.edit(content = None, embed=embed , view=None)```
#

i tried await interaction.followup.send(content = f'{ctx.author.mention}') as well to ping the author and then embed but same thing

slate swan
#

hi ,why this return 0
discord.Guild.sticker_limit

maiden fable
#

U need to do:

await inter.response.send_message(...) 
await inter.edit_original_message(...) 
left idol
#

i need the defer first but it wont let me do another response

maiden fable
#

Hm

maiden fable
slate swan
#

ye ofc

vale wing
#

Intents?

maiden fable
#

Nice, same for me

#

Prolly. Try enabling guild intents

slate swan
#

already true

vale wing
#

!d discord.Intents.emojis_and_stickers or smth

unkempt canyonBOT
slate swan
#

okay let me try

maiden fable
#

Nice

#

@left idol

#
await inter.response.defer() 
msg = await inter.followup.send(...) 
await msg.edit(...) 
slate swan
slate swan
#

sending and editing a followup is an unnecessary request

slate swan
vale wing
#

Disnaek top lib

left idol
#

i can't get rid of the msg the bot says that the application did not respond

#

and i thought i had to followup

#

maybe i just followup instead of edit

maiden fable
#

Yes u do

vale wing
maiden fable
slate swan
#

ye

stiff gorge
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: SyntaxError: 'await' outside async function (image.py, line 444)

          view = discord.ui.View()
          item1 = discord.ui.Button(
            label='Next meme',
            style=discord.ButtonStyle.blurple,
            custom_id='next')
          
          item2 = discord.ui.Button(
            label='End interaction',
            style=discord.ButtonStyle.red, 
            custom_id='exit')
          
          view.add_item(item1)
          view.add_item(item2)
          message = await ctx.send(embed=meme_opt(),view=view)
          
          while True:
            try:
               interaction = await self.bot.wait_for(
                'button_click',
                check=lambda inter: inter.message.id == message.id,
                timeout=30)
vale wing
#

Ok

cloud dawn
#

goes up to 30 if i recall.

slate swan
#

is it a glitch!?/

cloud dawn
slate swan
#

print(ctx.guild.sticker_limit,len(ctx.guild.stickers))

#

intents.emojis_and_stickers = True

maiden fable
#

Nice

cloud dawn
maiden fable
slate swan
rich kite
#

anyone know how to fix this?

maiden fable
slate swan
maiden fable
cloud dawn
stiff gorge
#

wait 1 min

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

cloud dawn
slate swan
#

what does this error mean, never have seen it before

stiff gorge
slate swan
slate swan
#

Legends say Ash lives in this channel.

slate swan
#

ive even reset it a few times and put it in and made sure

cloud dawn
slate swan
#

nvm client isnt a thing anymore. gotta change everything to bot

slate swan
slate swan
slate swan
#

smh

slate swan
#

which is untrue πŸ˜”

#

ye

#

or i just do check boost limit and get limit with that ;-;

cloud dawn
cloud dawn
slate swan
cloud dawn
#

Could you show how you run or start the bot?

slate swan
#

python main.py

#

and it usually loads

cloud dawn
#

I meant the function πŸ˜…

slate swan
#

wait.

#

i fixed it

#

forgot to close the terminal and reload it

slate swan
cloud dawn
#

Seems like a mistake I would make.

maiden fable
#

It's an API issue prolly. Ask in the API channel

slate swan
maiden fable
#

Nice

#

pip install py-cord[voice]

left idol
#
await interaction.response.defer()
# bunch of stuff 
await interaction.followup.send(content = None, embed=embed , view=None)```

tried this instead but now i get the application did not respond before clicking my button
cloud dawn
slate swan
#

2 am 😨

slate swan
left idol
#

im not getting any errors

cloud dawn
slate swan
#

uh ok

boreal ravine
maiden fable
boreal ravine
#

Disnake then

#

!d str.lower Use this

unkempt canyonBOT
#

str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.

The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
slate swan
#

never got this error before after a month of using this bot, fix?

slate swan
cloud dawn
#

Hmm I smell music bot.

slate swan
#

a part of the bot yes

boreal ravine
cloud dawn
#

We don't contribute making those here πŸ™„

left idol
#

await interaction.response.defer(invisible=True)
InteractionResponse.defer() got an unexpected keyword argument 'invisible'
is this not usable?

slate swan
#

looli its most probably the code from EvieePy's music cog gist

boreal ravine
boreal ravine
slate swan
#

everytime i see a voice related error being sent on discord. it reminds me of same

boreal ravine
cloud dawn
#

@boreal ravine You can stop knowingly contribute to a music bot.

rich kite
maiden fable
slate swan
shrewd apex
#

heroku?

slate swan
#

how to fix this error guys?

maiden fable
#

await client.load_extension

left idol
#

why does my bot still say this after the command is over?

slate swan
#

discord glitch

left idol
#

something with ctx.defer()?

slate swan
#

py-cord?

left idol
#

ye

slate swan
maiden fable
#

If should

slate swan
# left idol ye

defer is for awaiting a slash response, that specific feature is typing

left idol
#

but it isn't stopping even after all the stuff in the command is done?

slate swan
left idol
#

maybe i can followup too instead of send?

slate swan
left idol
#

slash command

slate swan
left idol
#

idk

slate swan
#

nice

slate swan
left idol
#

its still doing it so i'll try doing return

maiden fable
slate swan
slate swan
maiden fable
#

@left idol u need to send a followup to stop the bot from thinking

slate swan
#

Hunter is such a helpful person

left idol
#

ye i was gonna try followup

slate swan
slate swan
#

nvm tent

maiden fable
#

inter.channel.send sends a separate response that isn't connected to the slash command in any way

slate swan
#

tjen

left idol
#

ye got it to work

#

ty for help guys

slate swan
#

I'll go back to sleep instead

maiden fable
#

Nice

dapper tendon
#

why this error ?

maiden fable
#

U didn't add the bot scope while inviting the bot

#

@dapper tendon

latent yarrow
#

SyntaxError: positional argument follows keyword argument this the error

#

i get this error when

#
async def rps(ctx, member: discord.Member):
    embed = discord.Embed(title="",description ="",colour=discord.Colour.random())
    buttons = [f":rock:,:scroll:,:scissors:"]
    current = 0
    msg = await ctx.send(embed=embed[current])

    for button in buttons:
        await msg.add_reaction(button)

    try:
        reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author)
     
    except asyncio.TimeoutError:
        embed=embed[current]
        member.send("Play")
        await msg.clear_reactions()```
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval <code>
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

vale wing
#

Oh wait that's a part of lambda

latent yarrow
#

@vale wingwhy is that expression wrong

vale wing
latent yarrow
#

don't know

vale wing
#

Show the full traceback please

latent yarrow
#

wait now its working

#

wait

vale wing
#

Magic

slate swan
#

hi I have been getting this error a lot lately

someone help me with this?

  File "/workspaces/-------/project/project.py", line 1, in <module>
    import discord
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/__init__.py", line 25, in <module>
    from .client import Client
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/client.py", line 53, in <module>
    from .webhook import Webhook
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/__init__.py", line 12, in <module>
    from .async_ import *
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 46, in <module>
    from ..http import Route, handle_message_parameters, MultipartParameters, HTTPClient, json_or_text
ImportError: cannot import name 'handle_message_parameters' from 'discord.http' (/home/ubuntu/.local/lib/python3.10/site-packages/discord/http.py)```
vale wing
#

Can you like ```py plz

slate swan
#

it worked perfectly

slate swan
vale wing
#

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

vale wing
#

Anyway what version of lib did you install and how did you install it

slate swan
#
Traceback (most recent call last):
  File "/workspaces/69848642/project/project.py", line 1, in <module>
    import discord
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/__init__.py", line 25, in <module>
    from .client import Client
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/client.py", line 53, in <module>
    from .webhook import Webhook
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/__init__.py", line 12, in <module>
    from .async_ import *
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 46, in <module>
    from ..http import Route, handle_message_parameters, MultipartParameters, HTTPClient, json_or_text
ImportError: cannot import name 'handle_message_parameters' from 'discord.http' (/home/ubuntu/.local/lib/python3.10/site-packages/discord/http.py)

vale wing
#

And what did you use to install it

slate swan
slate swan
vale wing
#

Ok

#

It might be an issue with the library itself but as for now do you use venv

slate swan
#

thing is I'm making this for my project

#

so I am not really sure about anything atm

vale wing
#

Ok then do these

$ python3 -m venv venv
$ . venv/bin/activate```
Then install the required modules after there's (venv) in front of your command line
slate swan
#

oh wait

#

idk why but it's working now

vale wing
#

Probably was an issue with the library itself

slate swan
#

yeah I'm on 1.7.3 rn

vale wing
#

And uh do you need 2.0

slate swan
#

ss

slate swan
vale wing
#

I don't remember if you can use buttons in 1.7

slate swan
#

oh okay

vale wing
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
vale wing
#

@slate swan yeah it is 2.0+

slate swan
vale wing
#

Anyway consider looking into virtual environments (venv), using them is a good practice and helps with packages management

haughty wind
#

@bot.command() async def raffle(ctx, num: int): num = random.randint(1, 1000) await ctx.reply("You get" + (num))

#

hello i'm new to python and i am trying to code this bot one of it's features is a raffle

#

so i basically want it to go like this when i do p!raffle roll it picks a number between 1 and 1000

#

how do i fix it in here

lyric apex
#

!eval py import random num = random.randint(1,1000) print(num)

unkempt canyonBOT
#

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

342
lyric apex
#

Although That works fine nothing to fix there

haughty wind
#

it doesn't work

#

!eval

unkempt canyonBOT
#
Missing required argument

code

slate swan
#

anyone know why my nsfw cmds arent working, i can send the code if u want. i dont get a error at all when using it too

#

how do variables work within cog files with discord.py? am I able to use variables in my main file that loads the cogs or do the each individually have to be defined in each cog

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

proud apex
#

Can you suggest? How to make the bot write "Select a channel" when entering cmd, after the person specified the channel, the bot creates a webhook and now logs will be sent to that channel.

maiden fable
#

!d discord.Client.wait_for

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**...
shrewd apex
#

is multithreading possible in bot commands?

#

like making multiple api reqs at a time... using threads and getting back desired output

maiden fable
#

That's what asyncio is for

#

Threading and asyncio ain't the best friends lol

shrewd apex
#

u mean use asyncio.gather and then run in a an event loop?

maiden fable
#

Sure

brave flint
#

btw is that possible i can get the bot = discord.Bot(intents=intents) inside a cogs?
i mean i have 2 seprate file like main.py and db.py
and i wanna use bot.get_channel(id) in db.py

slate swan
brave flint
#

i dont get it rly

narrow grail
#

usually you can press a button multiple times but I can't. Everytime there is an interaction error (using pycord, already tried with discord_components and there was the same problem)

slate swan
dry crown
#

how do I set intents to true in a class Bot(discord.Client): ?

brave flint
slate swan
#
#db.py

def func1():
  store()...

def func2():
  read()...

like this?

brave flint
#
class RedditAutomation():
    def __init__(self):
        self.RedditAutomationDB = BlueskiesDB["RedditAutomation"]
        self.bot = bot```
slate swan
brave flint
#

uh that will be aufull

slate swan
#

it won't be

dry crown
#

guys can you help me

brave flint
#

ye lol ik"

slate swan
brave flint
slate swan
slate swan
brave flint
#

hmm like can i use *bot?

slate swan
#

noooo

brave flint
#

i mean not all func there need bot

brave flint
slate swan
brave flint
#

huh

#

my brain not responding fastly

brave flint
#

then just like add if bot : self.bot = bot

slate swan
#

no..

brave flint
#

so?..

#

i mean i will give RedditAutomation(bot).func() if the func need bot, and if not i just put RedditAutomation().funcs()

maiden fable
#

What u tryna do

#

@brave flint

#

And why tf are u consuming all the args in the bot var?

sullen pewter
#

What is better sublassing view or select

maiden fable
#

Depends on ur use case but View in most cases

sullen pewter
slate swan
short silo
#

how would i check if the Channel id provided as an input is accessible by the bot and is a text channel ?

slate swan
short silo
#

Also, if i get a channel as input.
<#xxxxxxxxxxx>
is what i get.
So, i have to get the integer only to use isinstance right ?

slate swan
#

you can just if channel.type == 0 to see if its a textchannel

#

uhh same thing, don't think either of them will have much impact on the time

#

Kannakillyourself btw, the if not channel check is useless here

#

!d discord.Client.fetch_channel cause an error is already raised if the channel does not exist

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_channel "discord.Client.get_channel") instead.

New in version 1.2.

Changed in version 2.0: `channel_id` parameter is now positional-only.
slate swan
#

eh, weird

#

imagine handling that instead

#

thats a web request and you get a 404 response so raising an error is something you should actually do

#

while the dpy server πŸ˜”

#

πŸ’€

#

Imagine

maiden fable
slate swan
maiden fable
#

Tbh, I wish the or operator worked for errors too. So smth like file = cond-1 or cond-2 (provided, cond-1 raises an error if the file isn't there, but sadly that's not the case)

slate swan
maiden fable
#

Right now I have to do smth like:

try:
    file = cond-1
except:
    file = cond-2
slate swan
#

bare exception

maiden fable
#

But like fetch_user raises one

slate swan
#

well

#

to return None

#

instead of raising an error

maiden fable
#

Ain't talking about dpy only

slate swan
#
from contextlib import suppress

with suppress(ErrorToHandle):
  ...
#

iirc contextlib is what is used

maiden fable
#

Might as well use try except instead

lyric apex
#

How to fetch vc ?

maiden fable
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
maiden fable
#

!d discord.Guild.fetch_channel

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread "discord.Guild.get_channel_or_thread") instead.

New in version 2.0.
slate swan
unkempt canyonBOT
#

@slate swan :warning: Your eval job has completed with return code 0.

[No output]
slate swan
#

but it'll run till the error isnt raised

maiden fable
#

Ig

slate swan
#

that's the only catch

lyric apex
slate swan
lyric apex
#

Owor_waah

maiden fable
#

Well I'm thinking of a scenario where u r using a lib method which raises an exception instead of returning None, so there u = some_lib.method() or 1 looks better rather than

try:
    w = some_lib.method() 
except Exception as e:
    w = 1
slate swan
#

Hunter writing essays

lyric apex
maiden fable
#

I'm on mobile, I hate the keyboard

maiden fable
#

Ik that's not how or works

#

I'm saying "I wish it worked like that"

lyric apex
#

401 bad request?

slate swan
#

isnt it unauthorized

maiden fable
#

I'm totally not using 200 for Internal Server Error

slate swan
#

yeah unauthorized

slate swan
maiden fable
slate swan
untold sigil
#

How can I do buttons instead of Reaction?

maiden fable
#

Not a maybe lol

maiden fable
#

Do u mean how to use buttons instead of reactions?

silk fulcrum
untold sigil
maiden fable
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
silk fulcrum
lyric apex
#

How do i trigger this event only when the content contains bot's command?

silk fulcrum
#

Using if?

lyric apex
#

Like?

slate swan
silk fulcrum
#

Like message.content.startswith(''prefix)

#

Phone is gud

lyric apex
#

):

silk fulcrum
slate swan
#

kanal = (channel_id1, channel_id2)
if message.channel.id in kanal

slate swan
silk fulcrum
#

Yeh...

#

Why (kanal) ?

slate swan
#

!e

c = (1, 2)
if 1 in (c):
  print("yes")
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

yes
slate swan
#

still works

lyric apex
#

Oh god

#

!d or

unkempt canyonBOT
#
or

6.11. Boolean operations


or_test  ::=  and_test | or_test "or" and_test
and_test ::=  not_test | and_test "and" not_test
not_test ::=  comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.

The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
lyric apex
#

When will this work lolzz_Sad_Cat ||this could be Another Method I Think||

slate swan
silk fulcrum
lyric apex
#

||Shorten Life Now Needs Simple thing ik||

slate swan
#

!e

my_uwu_channel_id_stored_in_a_really_really_long_variable_nobody_can_ever_think_of = (1,)
my_uwu_channel_id_two_stored_in_a_really_really_long_variable_nobody_can_ever_think_of = (2,)

if 1 in my_uwu_channel_id_stored_in_a_really_really_long_variable_nobody_can_ever_think_of and my_uwu_channel_id_stored_in_a_really_really_long_variable_nobody_can_ever_think_of in (1,) or 2 in my_uwu_channel_id_two_stored_in_a_really_really_long_variable_nobody_can_ever_think_of and my_uwu_channel_id_two_stored_in_a_really_really_long_variable_nobody_can_ever_think_of in (2,):
  print("uwu")
unkempt canyonBOT
#

@slate swan :warning: Your eval job has completed with return code 0.

[No output]
slate swan
#

sigh

silk fulcrum
#

Lohl

lyric apex
#

||Looks like leaving discord is only a way now||

silk fulcrum
#

Jwek

slate swan
#

me and my uwu variables, I love 'em all, equally

silk fulcrum
#

uwu

lyric apex
#

Ashley Has No Partiality ||Between|| Variables And Users

silk fulcrum
#

What Do You Mean

#

My English Is Not Understanding You

lyric apex
#

Sorry for my poor English

slate swan
lyric apex
slate swan
#

with an outcome of maximum fails to understand

#

hm

short silo
#

How would i check if a user exists ?

slate swan
#

!d discord.Client.fetch_user wont raise an error if it exists

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
short silo
#

alr, thanks

short silo
slate swan
#

stop using id keyword as a variable

granite parcel
#

how to delete my bot's reply when context usage is deleted

slate swan
#
from discord.ext import commands
import discord

class Test(commands.Cog):

    def __init__(self, bot, channel):
        self.bot = bot
        self.channel = channel

    @commands.command(name = "definir")
    async def teste(self, ctx, canal : discord.TextChannel):

        self.channel = str(canal.id)

        await ctx.send("Pronto!\nNome do canal: " + str(canal) + "\nID do Canal: " + self.channel)

    @commands.command(name = "enviar")
    async def sugestao(self, ctx, * , sugestao = " "):

        await ctx.send(channelID)

def setup(bot):
    bot.add_cog(Test(bot))```
#

discord.ext.commands.errors.ExtensionFailed: Extension 'commands.test' raised an error: TypeError: Test.__init__() missing 1 required positional argument: 'channel'

slate swan
maiden fable
slate swan
#

either do something like the python bot does

#

add a reaction to the messages

maiden fable
#

tho it's doable as long as the bots in a small server @granite parcel

slate swan
#

Hunter is so smart

granite parcel
#

delete

slate swan
#

no

maiden fable
# slate swan add a reaction to the messages

Adding reactions is more API calls than deleting command message on context since there's a possibility not always the msg is gonna get deleted but u gotta add a reaction on every msg and then delete the msg

slate swan
#

idk, I'm out, Hunter will help, he's the smartest

slate swan
# maiden fable Remove the self.channel and channel arg

but I wanted to make a command that allowed me to set the channel where the bot would send messages. For example: .defineSuggestions #channel (it would define a specific channel for the suggestions) and then .sendSuggest (sugestao) and it would send the suggestion in that channel

maiden fable
slate swan
maiden fable
granite parcel
maiden fable
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**...
granite parcel
#

event?

maiden fable
#

message_delete

granite parcel
#

on?

maiden fable
#

Or raw_message_delete

#

Wait I have an idaa

slate swan
#

with a list of message IDs

maiden fable
#

await bot.wait_for("raw_message_delete", check=lambda payload: payload.message_id == ctx.message.id, timeout = None)

slate swan
#

ew

granite parcel
maiden fable
#

I first had the thought of using that but there's a possibility that isn't gonna work

maiden fable
#

That's why I used that lol

slate swan
#

if it has to be done in every command that is

maiden fable
#

Using a botvar and making a dict?

granite parcel
#

adding this to every cmd is gonna take long time

slate swan
slate swan
granite parcel
#

yeah

slate swan
# granite parcel yeah

consider making a bot variable (run !botvar for more info) that holds a dictionary of the format {message_id: channel_id}, and use the on_raw_message_delete event (run !d discord.on_raw_message_delete for more info) event to check when a message was deleted, and if the deleted message's id was found to be in the (bot) variable that holds the dictionary, get/fetch that message and delete it

granite parcel
#

lemmie see

slate swan
#

get/fetch that message and delete it
πŸšΆβ€β™‚οΈ bot.http.delete_message(channel_id, message_id) saves an extra api call

slate swan
#

imagine using dpy

granite parcel
#

in 2.0 we have to use await for loading extension?

granite parcel
#

nthg

#
    await client.load_extension(extension)
    ^
SyntaxError: 'await' outside function```
#
if __name__ == "__main__":
    for extension in extensions:
        try:
           await client.load_extension(extension)
        except Exception as e:
            print(f'Error Loading {extension}', file=sys.stderr)
            traceback.print_exc()```
#

how to fix it

#

@slate swan.

slate swan
#

use an async function to start your bot or setup hook

#
import asyncio

async def main():
  async with client:
    for extension in extensions:
      await client.load_extension(extension)
    await bot.start("TOKEN")

asyncio.run(main())
#

or setup_hook

granite parcel
#

ImportError: cannot import name 'InvalidArgument' from 'discord' (/home/container/.local/lib/python3.8/site-packages/discord/init.py)

shrewd apex
#

using replit i got setup tools deprecated error any idea why?

maiden fable
shrewd apex
#

when i tried to run it just gave use standard tool pip to build....

untold sigil
#
async def join(ctx):
    channel=ctx.message.author.voice.voice_channel
    await bot.join_voive_channel(channel)
```The bot doesn't join to the channel
where is the mistake?
maiden fable
maiden fable
shrewd apex
#

yeah will do after dinner

maiden fable
#

!d discord.VoiceState.channel

unkempt canyonBOT
#

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

maiden fable
narrow grail
#

idk why. I actually nothing changed to my bot but now it is only working in direkt messages but on server I don't get a response

vale wing
#

And yeah what was the last time you launched your bot and it ran successfully

narrow grail
#

of course

vale wing
#

Message content intent enabled?

narrow grail
#

I only switched to a new library (pycord) but first when I started it with some things from pycord in it, it worked fine

narrow grail
vale wing
#

Create on_message listener and try printing out messages data

shrewd apex
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

shrewd apex
shrewd apex
maiden fable
shrewd apex
#

hmm i see

maiden fable
#

U ran this yourself?

shrewd apex
#

no

vale wing
#

Poetry stuff

maiden fable
#

Yea

shrewd apex
#

i just made a requirements.txt and installed it in shell thats it

maiden fable
#

There is a poetry file, can u share that?

shrewd apex
#

u know any other hosting service?

maiden fable
#

Do u have a cc?

vale wing
#

Samovar server

shrewd apex
maiden fable
maiden fable
vale wing
#

The thing I host my bots on

shrewd apex
#

smh i dont

maiden fable
#

Lol okay okay

vale wing
#

Self hosting

maiden fable
#

Its a pain tbh

shrewd apex
vale wing
#

The only pain is to setup network

maiden fable
#

Indeed

maiden fable
shrewd apex
#

mhm ok

narrow grail
shrewd apex
#

its under constructionπŸ’€

#

the website for danbot

maiden fable
#

Rip

wide thunder
#

hm

vale wing
wide thunder
#

hi

maiden fable
#

Hi

vale wing
#

Hello

narrow grail
vale wing
#

Listen is better

#

For event you have to process_commands

narrow grail
vale wing
#

In listen you don't

narrow grail
#

i know

maiden fable
vale wing
#

Disable pass length limit

maiden fable
#

How

vale wing
#

Google (idk myself)

maiden fable
#

Okay thanks

narrow grail
vale wing
#

No message content intent

#

Show how you enabled intents please

narrow grail
vale wing
#

message_content isn't included into default

#

You need to explicitly enable it like you did with members

narrow grail
#

but it worked fine without it a few hours ago and also the last months?

vale wing
#

The last months probably

#

A few hours ago I have no idea

#

You could've changed a slight thing and didn't even notice it

narrow grail
#

I started working with buttons and for this I had to add a library

vale wing
#

Let me guess - before you used dpy 1.7

narrow grail
#

no after

vale wing
#

You couldn't have been using it after - it doesn't require you to explicitly enable message content intent, that's why it worked :)

narrow grail
#

ok ok I try to enable it

#

hmmm same problem. Nothing changed

vale wing
#

How did you enable it

odd mango
vale wing
#

Replit is very very very cringe for hosting bots

odd mango
#

its not if you know your stuff πŸ‘€

#

my bot almost never dies

vale wing
#

429 error code knows its stuff

slate swan
#

🧒

narrow grail
odd mango
vale wing
vale wing
odd mango
# slate swan Impossible

well, when u kill container and restart repl, it starts off with a new container and new shared ip

#

kill any 1-14

#

i do that for my bot its chill

narrow grail
slate swan
odd mango
#

anyways, i agree REPL IS SHIT. but its good if you know what to do and dont have money

vale wing
#

Ok cool

slate swan
#

If u want someone to copy ur code

vale wing
#

I should probably insert new CPU inside my server

odd mango
vale wing
slate swan
#

Rip

vale wing
#

@odd mango hold up, what about replit's ephemeral file storage

slate swan
#

Ye it's good

#

Good for tokens