#discord-bots

1 messages Β· Page 1077 of 1

slate swan
#

Yes.

sick birch
#

server status?

full lily
#

yeah status I guess

sick birch
#

Not aware of any tools that can do that, I'm sure some exist though

slate swan
#

But how would i make the a cmd?

full lily
#

you can do it through command prompt

slate swan
#

I want it to be cmd for my bot but i have no clue how.

full lily
#

you'd probably use subprocess to be able to evoke a terminal command

sick birch
full lily
#

then capture the output. I'm sure they have a method for that

sick birch
#

I can't tell you if it's any good, you can be the judge of that

slate swan
#

It wont be as easy as it is on py its thru a discord bot and i have no clue on how too.

#

like in general if you understand.

full lily
#

a raspberry pi?

slate swan
#

Lemme send you something in here

#

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="google.com"))

#

Like that

#

For a example

#

But i want to be able to ping a ip address and receive a up or down status but idk how too

sick birch
#

Probably use the tasks extension to periodically ping it

#

and adjust status accordingly

past aspen
#

!e ```py
from discord.ext import commands

client = commands.Bot(commands_prefix=['thing'], help_command=None, case_insensitive=True)

client.run("thing")```

unkempt canyonBOT
#

@past aspen :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
past aspen
#

sad

slate swan
#

why did you pass a list to the command_prefix kwarg

#

its literally just one element?

#

and nice instance naming

past aspen
#

!e ```py
import os

os.system('cd /')
os.system('ls')```

unkempt canyonBOT
#

@past aspen :warning: Your eval job has completed with return code 0.

[No output]
past aspen
#

oh yea i meant command_prefix

#

!e ```py
import os

os.system('ls')```

unkempt canyonBOT
#

@past aspen :warning: Your eval job has completed with return code 0.

[No output]
velvet compass
maiden fable
#

5 reactions πŸ‘€

polar scroll
#

Hey guys, i wanna start making bots in python, is it better/easier than Node.js?

past aspen
maiden fable
polar scroll
#

Welp, i know some stuff in python, but nothing about node.js

maiden fable
#

Well its yr choice ultimately

slate swan
#

ill say python would be easier because of its easy to understand syntax

#

djs is easy too

sick birch
#

I find d.js to be lower level, so maybe not as easy

#

It's closer to the API, if that makes sense

#

Also you're asking in a python server

slate swan
#

Why on_invite_create is not working? I made it print the guild id but it doesn't work

#
@bot.event
async def on_invite_create(invite):
    print(invite.guild.id)```
#

iirc it needs manage_guild permissions, i may be wrong

#

!d discord.on_invite_create

unkempt canyonBOT
#

discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite "discord.Invite") is created. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") rather than the respective models.

This requires [`Intents.invites`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.invites "discord.Intents.invites") to be enabled.
slate swan
#

All intents are enabled

#

yeah, manage channels

#
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)```
#

I have all the intents enabled

flint isle
#

im looking for basic code for reading and writing to a json file using a bot command

slate swan
#

not Intents, manage_channel Permissions

#

for the channel invite is created in

#

Ok

slate swan
#

!d json.dump

unkempt canyonBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").

The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.

If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
flint isle
#

thank you i will implement that

slate swan
#

What on_guild_join and remove do?

terse coyote
#

how to open .db-journal file sqlite3?

slate swan
#

why would you open the db-journal file

slate swan
terse coyote
sick birch
sick birch
slate swan
slate swan
sick birch
sick birch
#

are you gonna dump the binary file 😳

#

(or whatever weird encoding it's in)

slate swan
#

nah, some webservers allow opening it, all you see is just bytes~

#

enjoy reading

maiden fable
#

o

#

what's a db-journal file tho @slate swan

slate swan
maiden fable
#

Ah

wet crystal
#

Why is ctx.author.voice.channel.members not working anymore and saying

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
torn sail
regal pulsar
#

!d disnake.Member.voice

unkempt canyonBOT
wet crystal
#

any1 know how to assign a role to a member?

neat mist
#

im not sure but have a question of my own

#

will say after

torn sail
unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
neat mist
#

ok ill ask now

#

this is gonna seem rlly stupid but

#
async def randint(message):
    general_channel = client.get_channel(##################)
    if "_randint" in message.contents:
        await general_channel.send("From?")
        @client.command(name="startint")
        async def startint(message):
            general_channel = client.get_channel(##################)
            x = message.content
            await general_channel.send("To?")
            @client.command(name="endint")
            async def endint(message):
                general_channel = client.get_channel(##################)
                y = message.content
                xy = random.randint(x,y)
                await general_channel.send("xy")
    else :```
#

why doesnt this work?

full lily
#

which part of it

#

the indentation looks off

neat mist
flint isle
neat mist
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.

neat mist
#

do i put around it?

steep drift
#

Can someone please help me in #help-potato it's an issue with a discord bot.

neat mist
#

my code prob way off but im trying to make it so it asks follow up questions and turns the answers into variables

fading marlin
neat mist
#

ok im not sure what that means im a complete beginner but here are my full intentions

steep drift
neat mist
#

essentially i want a command that makes a random number generator. The first part is to activate the command which should work fine. The second and third part asks for the first and second integer which is how low and high the number generated in the end can be. These numbers would ideally be stored as variables in the code and be used in the the part, which just outputs a random number with the limitations previously made. Im trying to make it so it first asks "From?" which is where u say the first number and its stores it (x). Followed by that is "To?" which is the second number also stored as a variable (y). Then these numbers would be put into the generator and it would work

#

not sure how to properly code this so i tried and googled multiple times but i dont get it

#

ver confusing stuff ):

fading marlin
fading marlin
#

yeah, dpy isn't exactly a library for beginners...

neat mist
#

true

#

ig i was too ambitious

fading marlin
#

🀷

neat mist
#

WAIT COMMANDS.CONTEXT IS A THING

#

im so dumb

slate swan
#

How can I add numbers in a row in list? E.g

1)
2)
3)
...

sick birch
#

using enumerate()

regal pulsar
sick birch
# sick birch using `enumerate()`

!e

myList = ["item 1", "item 2", "item 3"]
text = ""
for index, item in enumerate(myList):
  text += f"{index + 1}) {item}\n"
print(text)
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

001 | 1) item 1
002 | 2) item 2
003 | 3) item 3
sick birch
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

001 | 1) item 1
002 | 2) item 2
003 | 3) item 3
sick birch
#

Shorter, hard to read

royal meteor
#

For embed pagination, how would I split 4 commands per page?
So far I got this:

commands_list = [command for command in self.bot.walk_commands()]```
but have no clue what to do next.
flint isle
#

Can i see what the highest number that is stored as the name is?

{
  "1": "heh",
  "2": "hehv2"
}

Also when i add something to it via a command does it automatically format it like:

"3": "hehv3"```
sick birch
#

A dict with numbers as keys is basically a list but with extra steps

flint isle
#

will i be able to auto add to lists in json

sick birch
#

Saving to a file?

flint isle
#

yes

sick birch
#

Well there's no such thing as "adding" in a JSON file

#

The entire content of the file has to be deleted, then rewritten from start to finish

flint isle
#

... what is reccomended for me to store the stuff in then

sick birch
#

A database

flint isle
#

im using google realtime database

#

will pulling every 30 seconds be ok?

sick birch
flint isle
#

no their realtime version

sick birch
#

Hm, well I'm unfortunately not experienced with that

#

I've only worked with SQL databases

flint isle
sick birch
#

Not sure, again not experienced

#

Postgres does support lists, so there's that

flint isle
#

well im looking for something that will be cloud hosted. I cant exactly pay or activate most free tier stuff due to not having my debit card yet.

neat mist
#
async def number(ctx: commands.Context, min: int, max: int):
    await ctx.channel.send(random.randint(min, max)) ```
#

about this how can i set the integers i dont get it

sick birch
#

Set what integers?

neat mist
#

min and max

#

im not sure how it works someone sent me this

sick birch
#

Call the command from Discord using this syntax:

<command_prefix>number <min> <max>

for example:

!number 0 10
royal meteor
#

For embed pagination, how would I split 4 commands per page?
So far I got this:

commands_list = [command for command in self.bot.walk_commands()]```
but have no clue what to do next.
flint isle
#

does anyone have any cloud based databases that are reccomended

#

@sick birch can you give me an example of a database list

#

so i can see if the database im using supports it

sick birch
#

What do you mean?

flint isle
#

a list in a database

#

im trying to add one to my database to see if it enters correctly

sick birch
#

Err.. I don't have a postgres database lying around with a list in it unfortunately

flint isle
sick birch
#

Like the SQL query?

flint isle
#

idk

sick birch
#

Sorry, I'm not fully understanding what you're asking me

flint isle
#

this is all my database has to offer in case of adding stuff

flint isle
sick birch
#

Can you tell me about the nature of the information you're storing?

#

There may be a better way

#

E.g is it dynamic, do you allow other users to change it, etc

flint isle
#

different statuses the bot can have

#

other information that needs to be stored for some reason

sick birch
#

Can users change the list?

flint isle
#

yes

sick birch
#

Hmm yeah if the users didn't change it it would be very easy

#

You wouldn't need a database or a JSON file even

flint isle
#

i just need the posibility of them adding stuff

#

they dont need to edit entries at least

sick birch
#

I suppose you could just have a one column table

#

Which is equivalent to a list

flint isle
#

in the database?

sick birch
#

Yes

flint isle
sick birch
#

Just create a table as usual, add only one column of strings

flint isle
#

Ok

#

Now how would I pull a random one out of that list

sick birch
#

If you can get the data from the database into your python code as a list, a simple random.choice() will do

flint isle
#

Ok

#

I will try all of that when im back at my system and I will let you know

flint isle
#

also is there a way to have


import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred)

in all my cog files automatically?

slate swan
#

it says this when I check for errors

#

and I dont know how to fix it

#

I'll send the lines

#
        prefix = 'g!' 
        version = '1.0.0'
    owner = '625025751413948436'    
    owner_name = 'Clicks#8882'    ```
#

@sick birch

sick birch
#

Yeah notice how the lines are all over the place

slate swan
#

idk how to fix them

#

if I mess around with indents

sick birch
#

Just make sure they're all indented on the same level

#

e.g the first letters all start in the same place

slate swan
#

oh okay. ty

stiff fern
#

Question on how I can check the value of a parameter in the case the user inputs a invalid response bc rn I try to type .purge d it will return an error saying couldn't find d as a member or something like that, I tried using a try except but it doesn't catch it in this case so what would you do?

# Event on [clear] command usage
@client.command(aliases = ['clear', 'purge', 'delete'])
async def clear_chat(ctx, member: discord.Member = None, amount: int = 5):

    try:
        if member is None:
            await ctx.channel.purge(limit = amount)
            await ctx.send(f'{amount} messages have been cleared.')
        elif not member:
            print('test')
    except:
        print('Error')
visual island
stiff fern
#

So is that a separate thing then, wouldn't be apart of this function

visual island
stiff fern
#

So I found a script on google and it's a class w/ listeners and cogs and some other random stuff I haven't seen before so I'm curious as to how this script would know there's an error? Is there an event that catches it when it comes in and then basically translate it to whatever you have it to return as?

sturdy kraken
#

you can raise your own errors

#

if you want one when someone does .purge d or whatever

slate swan
#

why would you catch an error and raise your own?

sturdy kraken
#

Β―_(ツ)_/Β―

slate swan
visual island
slate swan
visual island
slate swan
#

@visual island isn't Kobo Kanaeru a vtuber?

visual island
#

Mhm

slate swan
#

y9su is sus😳

slate swan
#

you sure you dont watch her🀨

#

i dont..

#

lmao

lyric apex
#

Is there any event in dpy that happens every second?

sick birch
#

No, why?

visual island
#

No, just use tasks.loop

sick birch
#

What's the use case?

slate swan
#

jeez you guys are fast

lyric apex
#

I wanted to get the guild id from the event

slate swan
#

only thing that happens on the background consistently is hbs and its mostly every 4.5 seconds

visual island
slate swan
slate swan
#

😳

lyric apex
sick birch
slate swan
visual island
slate swan
#

no ids change

sick birch
#

Discord snowflakes never change

slate swan
#

hence the name snowflake

sick birch
#

Well the name snowflake comes from the fact that every ID is guaranteed to be unique

slate swan
#

no

sick birch
#

Sort of like a snowflake, which is unique

slate swan
#

it comes from a snowflake

#

a snowflake is always unique like Robinpithink

#

Robin is a unique lad that no one is exactly like himpithink

sick birch
#

thank you 😊

slate swan
#

doesnt mean its a good thinglemon_glass

#

??

sick birch
#

😦

slate swan
#

take it as a compliment tho

lyric apex
dusky pine
#

poor robin

sick birch
#

πŸ˜„

lyric apex
#

Cmds

sick birch
#

Ah

#

You can just use asyncio.sleep() for that though it's error prone

lyric apex
visual island
#

Everything resets after restart if you don't use a db

sick birch
#

That's the problem

slate swan
visual island
#

They understood what I meant, right kobopien

heavy shard
#

is there anything against connecting to database asynchronously in cog's __init__ -> bot.loop.create_task?

slate swan
sick birch
heavy shard
#

aww shucks.... i'd like to avoid bot's setup_hook to make the cog sort of independent module

slate swan
#

depends on the situation

sick birch
#

Other than the fact that it's not the right place, usually your connector of choice is going to return the connection object after it's connected

slate swan
#

i made a whole db client class shipit

heavy shard
#

i see

sick birch
#

And create_task doesn't wait for the connection to finish, unless you explicitly await it, which defeats the whole point of putting it inside the __init__

heavy shard
#

ol' good setup_hook then?

sick birch
#

you know it

heavy shard
#

thanks for an advice πŸ™‚

slate swan
#

you dont need to subclass the Bot class btw

#

if thats what youre worried about

stiff fern
#

so I realize you could do @command.error and that's how you'd catch em, are you able to use a for loop then to basically repeat that for every command

dusky pine
slate swan
stiff fern
#

Oh I see

slate swan
dusky pine
#

Oh yeah it looked wrong lol

slate swan
#

!d discord.discord.ext.commands.on_command_error

unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
stiff fern
dusky pine
#

yep

#

i think? idk

#

im a bit rusty in dpy

slate swan
sick birch
# stiff fern ?
@bot.event
async def on_command_error(...):
  ...

i haven't done dpy in forever so I apologize if that's wrong

slate swan
#

if you forgot them

sick birch
#

Just too lazy to type them out

slate swan
sick birch
#

Either way their problem isn't with the parameters

flint isle
#

im trying to import a conf.json from the following file tree

wb.py
config.json
cogs
^-events.py <this file needs to refrence config.json->

this is the code that needs to refrence it


import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred)
stiff fern
#

So when it comes to parameters and player commands

If you can have 2 parameters, being a members name/tag and the second being a int

Both are optional but if I wanted to input the int w/out the player name/tag how would I get it to recognize that the int belongs with the the second parameter and not the first

#

Or is that what
parameter: str
parameter: int
does

sick birch
#

I don't believe that's possible without manually figuring it out

#

You could make the integer the first argument however

stiff fern
#

yea alright I didnt know if there was some method for that

stiff fern
#

Oh one more thing, what does pass_context = True mean

sick birch
stiff fern
#

o

sick birch
#

You usually don't need it anymore

stiff fern
#

alrighty

#

Is it better to do Value = None or Value is None or does it matter

#

Also how do you know what error classifies as?

slate swan
stiff fern
#

Or do you just learn that as you go

slate swan
#

== checks the value of the object while is checks the identity of the object

stiff fern
#

Is the identify the value type

#

Or is that something different

slate swan
#

not quite it checks the id of the object

lyric apex
#
if data == None:
if data is None:```
Mean the same?
stiff fern
#

nope

slate swan
unkempt canyonBOT
#

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

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True False
lyric apex
#

Lol i was telling it with examplezz_udaas

slate swan
#

see how the first on is true and the second one is false

lyric apex
stiff fern
#

ooh == checks the value is sets the value

slate swan
#

no no

stiff fern
slate swan
# slate swan !e print(0 == False, 0 is False)

here if you didnt know 0s bool value is False, see the value is equal because 0 is False and False is equal to False and the second one is False because 0 isnt exactly the bool type False

lyric apex
#

Usually We Use is for Nonetype object

slate swan
#

NoneType*

lyric apex
#

v_cat πŸ‘

torn sail
slate swan
stiff fern
#

So if you want to set a value to None then you just do Value = None

sick birch
#

Sometimes they won't literally be the same, take some discord models for example. A discord.Member, at 2 different times, may not necessarily be the same (left guild, got new roles, changed name, etc) yet discord.py implements it in such a way that it is still the same (most likely by ID)

#

You can also just do something completely goofy like

def __eq__(self, other):
  print("this is silly")
  return False
stiff fern
sick birch
#

Generally is is used for checking NoneType as it's a singleton iirc

#

If you want to be shorthand, you can just do something like

noneVar = None
if not noneVar:
  print("None!")
#

That may be less readable to some, you be the judge of that

stiff fern
#

ah i see graci

pliant gulch
supple thorn
#

Infect

lyric apex
#

That means == is comparing between the variables and is checks the value

heavy shard
#

"is" checks identity

lyric apex
#

Yeahcute_cat

slate swan
#

!d is

unkempt canyonBOT
#
is

6.10.3. Identity comparisons

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. 4

slate swan
heavy shard
# slate swan

it seems you used json as a function name, overwriting json module

#

just change the function name to something else

sick birch
slate swan
sick birch
#

you do with your time however you please

slate swan
#

exactly 😑

keen talon
#

Where chat

sick birch
#

gone

slate swan
#

like your ...

slate swan
#

πŸ‘€

slate swan
#

Chill go take some sleep

#

How can I do like
If the user who sent the message if his id is in particular file then bot would do stuff

#

Like if user name/id in .file do this if not do this

slate swan
#

I mean where u store ids

slate swan
slate swan
robust fulcrum
slate swan
#

do u have loaded it somewhere

#

nope

#

uh ok gimme a min

slate swan
#
with open("ids.txt") as w:
  if "hi" in w.readlines():
       print("its there")
  else:
      print("not there")
#

try it not sure tho

robust fulcrum
# robust fulcrum https://media.discordapp.net/attachments/971701505948282890/981217653077213294/c...
import discord
from discord.ext import commands
from matplotlib import pyplot as plt
import numpy as np

def check(msg):
  return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id

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

    
	@commands.command()
	async def pie(self ,ctx):
		def check(msg):
			return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id
		initial = 1
		cars = []
		await ctx.send("enter number of labels")
		nop =  await self.bot.wait_for('message', check=check,timeout=20)
		nov = int(nop.content)
		while initial<=nov:
			await ctx.send("enter the value of pie chart to append")
			apens = await self.bot.wait_for('message', check=check,timeout=20)
			cars.append(apens)
			initial = int(initial+1)
		initials = 1
		data = []
		await ctx.send("enter number of data")
		nops =  await self.bot.wait_for('message', check=check,timeout=20)
		novs = int(nops.content)
		while initials<=novs:
			await ctx.send("enter the values of labels according to order!")
			apenss = await self.bot.wait_for('message', check=check,timeout=20)
			apenss = int(apenss.content)
			data.append(apenss)
			initials = int(initials+1)

		fig = plt.figure(figsize =(10, 7))
		
		plt.pie(data, labels = cars)
		
		plt.savefig("chart.png")
		
		await ctx.send(file=discord.File("chart.png"))

	
async def setup(bot):
    await bot.add_cog(pie(bot))

Guys i made a command which can send pie charts as well as we can make charts but my bot is not sending things in list [cars] instead it's sending me things in the above pie chart image
Can anyone help me

#

Done

#

Let me run it

robust fulcrum
slate swan
#

Ty

slate swan
#

Hi sparky

slate swan
#

sparky always slaps

slate swan
#

it's doesnt have .content

robust fulcrum
#

Oof

slate swan
robust fulcrum
#

Should I convert that to str?

#

And are you from India btw?

slate swan
#

Ye?

robust fulcrum
#

Cause live insaan server i saw

#

Why .content is important?

slate swan
#

Does the footer field of an embed support masked links?

slate swan
#

sry for caps

slate swan
# robust fulcrum Why .content is important?

Because: Every message (for example this message) contains a whole lot more data than just me writing this message and you seeing the words (content of the message), there's author id (my id) embeds, though user accounts cant send any, attachments, which are a held by an ideal data class which has all the propertied that represent these models, so using .content returns the content of the message, as its a property in that class which can be accessed to see the content of the message, same goes for attchments, embeds, etc.

#

😳 paragraph

robust fulcrum
slate swan
#

dead on

robust fulcrum
#

What

slate swan
#

Lol

#

i mean, correct

#

does the name field support hyperlinks?

#

ye

slate swan
slate swan
robust fulcrum
#

@slate swan thank u bro

slate swan
#

yes.

robust fulcrum
#

My pie chart command is finished finally

slate swan
#

πŸ‘

robust fulcrum
#

Here is image of it

slate swan
stone beacon
slate swan
#

blocking command uwu

slate swan
robust fulcrum
slate swan
#

bot.remove_command("uwu")

slate swan
#

weirded

#

I thought they weren't supported

#

and you needed to just add field

#

I started learning pillow but can't understand the docs 😐

#

πŸ’€

slate swan
#

with an invis name

slate swan
slate swan
#

I need an invis name then

#

just pass ** ** to the name

slate swan
#

Β―\_(ツ)_/Β―

slate swan
#

I just copied some invisible character online

#

It seemed to work

#

totally your wish

#

do you know of any interesting rest apis

#

some random api? maybe

robust fulcrum
slate swan
slate swan
robust fulcrum
#

I want to use Oxford api but don't know how to

slate swan
slate swan
slate swan
slate swan
#

gotta search it up brb

robust fulcrum
#

Like urban dictionary

slate swan
#

arent there other apis for that

robust fulcrum
#

For what

slate swan
#

get information on the word

slate swan
slate swan
#

no., but you can search the website rapidapi for a number of apis , im sure of that one

slate swan
#

sparky confused

#

I mean in embed we use this

#

yes I know

#

for a hyperlink

#

uh

#

nvmd

#

he aint wrong

#

does anyone know of any weather apis that dont require api key

slate swan
slate swan
#

okay...

robust fulcrum
#

Guys why this is coming when i run my bot?

slate swan
#

replit issue

robust fulcrum
#

Oof

#

😣

slate swan
#

literally is an api with lists of other apis

maiden fable
#

There is a GitHub repo too

slate swan
maiden fable
slate swan
#

Sweet!

robust fulcrum
#

Guys how can we use light blue color in pil for sending image in dpy

magic pond
#

is this correct ?
avatar = BytesIO(await user.avatar.url_as(size=128).read())

shrewd apex
robust fulcrum
#

I using bytesio but still don't know it's use :(

alpine pewter
#

Is there anything like a channel.followup_send(...) etc
Or is it just channel.send(...)?

maiden fable
#

!d discord.Interaction.followup

unkempt canyonBOT
maiden fable
#

Do interaction.followup.send

lament depotBOT
#
You blew it.

@obtuse obsidian, please enable your DMs to receive the bookmark.

slate swan
#

uhh

stiff fern
#

How would you whitelist the command usage when using .purge()

#

So it doesn't delete the message that used the command

maiden fable
#

check kwarg

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, 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 the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

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

Examples

Deleting bot’s messages...
stiff fern
#

grraci

maiden fable
#

check=lambda msg: not msg.startswith(bot.command_prefix) or smth

#

Tf does that even mean

alpine pewter
# maiden fable For slash commands?

Yes, sorry.
I'm trying to send an embed for a for-loop in a channel but when I do it, it sends multiple. Unsure how to fix it, tried different embeds.

maiden fable
#

Wym it sends multiple?

slate swan
alpine pewter
#

Instead of sending one giant one, it just sends multiple.
So, it's in the loop but when I take it out, it only sends the first item.

maiden fable
#

Great transition of mine from a Hunter to a Frog lmao

slate swan
#

thanks :)

alpine pewter
#

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

maiden fable
unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
slate swan
alpine pewter
maiden fable
#

Yea u need a str.join

#

And a list comp

slate swan
#

and indenting is the issue as expected.

maiden fable
#

Where

alpine pewter
#

It works perfectly fine when I just have it send in a text format but when I do an embed, it doesn't work. I'm gonna check both πŸ˜„

slate swan
maiden fable
stiff fern
slate swan
stiff fern
#

The only time I see lambda is with list or somethin

maiden fable
stiff fern
#

oh I see

maiden fable
#

!d lambda

unkempt canyonBOT
#

An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression

alpine pewter
slate swan
#
await channel.purge(check=lambda msg: msg.id != ctx.message.id)```
alpine pewter
# slate swan await channel.send

So, I don't understand fully.
When I don't have an embed, it sends fine.
await channel.send(value)
When I add one, it sends multiple values instead of one giant embed. What would I need to do then?

magic pond
#
    @commands.command(invoke_without_command=True, aliases=['UI', 'uinfo', 'info', 'ui'])
    async def userinfo(self, ctx, *, user:discord.Member = ''):
            if user == '':
                user = ctx.message.author

            if isinstance(user, discord.Member):
                role = user.top_role.name
                if role == "@everyone":
                    role = "N/A"
                voice_state = None if not user.voice else user.voice.channel
            if True:
                em = discord.Embed(timestamp=ctx.message.created_at, colour=0x2F3136)
                em.add_field(name='**User ID**', value=user.id, inline=True)
                if isinstance(user, discord.Member):
                    em.add_field(name='**Nickname**', value=user.nick, inline=True)
                    em.add_field(name='**Status**', value=user.status, inline=True)
                    em.add_field(name='**In Voice**', value=voice_state, inline=True)
                    em.add_field(name='**Game**', value=user.activity, inline=True)
                    em.add_field(name='**Highest Role**', value=role, inline=True)
                em.add_field(name='**Account Created**', value=user.created_at.__format__('%A, %d. %B %Y  %H:%M:%S'))
                if isinstance(user, discord.Member):
                    em.add_field(name='**Join Date**', value=user.joined_at.__format__('%A, %d. %B %Y  %H:%M:%S'))

                em.add_field(name=("Created on {} ({} days ago)".format(user.created_at("%d %b %Y %H:%M") (ctx.message.created_at - user.created_at).days)))
                em.set_thumbnail(url=user.avatar.url)
                em.set_author(name=user, icon_url=user.avatar.url)
                await ctx.send(embed=em)
#

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'datetime.datetime' object is not callable

slate swan
#

.format('%A, %d. %B %Y %H:%M:%S') why not use strftime?

#
  • user will never be a discord.User since you typehinted it to Member
stiff fern
#
@client.command(aliases = ['clear', 'purge', 'delete'])
async def clear_chat(ctx, amount: int = 5, member: discord.Member = None):
    if ctx.message.content.startswith(client.command_prefix):
        print('Works')
    else:
        await ctx.channel.purge(limit = amount)
        await ctx.send(f'{amount} messages have been cleared.')

So I was able to format the if statement with startswith, but it wouldn't actually change what it purges so it doesn't include that message, do I need to do something inside of purge() or am I suppose to use a for loop

slate swan
#

just make a check

stiff fern
#

wym

#

βœ…

slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, 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 the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

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

Examples

Deleting bot’s messages...
slate swan
#

the check kwarg

stiff fern
#

Oh I see

sullen pewter
#

what does background task do?

maiden fable
sullen pewter
maiden fable
#

The code u write?

sullen pewter
#

is it useful

#

why

maiden fable
#

Yea

sullen pewter
#

what's the point of running it in the background repeatedly

slate swan
sullen pewter
#

any examples?

maiden fable
maiden fable
unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
maiden fable
slate swan
#
from discord.ext import tasks 
channel = bot.get_channel(id)
@tasks.loop(seconds=59)
async def uwu():
    await channel.send(...)

uwu.start()```
sullen pewter
#

ok ty

slate swan
#

imports ik

#

noo

#

channel variable is None

slate swan
#

πŸ˜‚fine

#

but why would it be None

#

cause a global level get_x method will return None as the cache has not been setup yet

#

oh uhh yeah my bad

#

and it will be a static variable ( with get called only once)

stiff fern
# slate swan !d discord.TextChannel.purge
await ctx.channel.purge(limit = amount, check = lambda msg: not ctx.message.content.startswith(client.command_prefix))

So here's what I tried, doesn't really work if you see something obvious

slate swan
stiff fern
#

I tried changing some stuff around but couldnt find it shrug

stiff fern
#

o

#

oh well thats way off what I had lol

slate swan
#

over-complicated isnt it

stiff fern
#

i suppose so

visual island
maiden fable
#

No harm in getting the channel in the task itself and adding a wait_until_ready at the top

#

Hi there icy

visual island
#

kobopien why do people know me as icy, but hi

maiden fable
#

Lmao cz it was a better name

visual island
#

okay kobopien

alpine pewter
maiden fable
#

Have u read the tag on how to use join?

alpine pewter
#

I just checked out what you sent me, I didn't understand it, so, I pulled up a video.
I'm unsure how it would work in my code though to make it work.

maiden fable
#

Ah so can you paste the for loop here?

alpine pewter
#

Will do, do you want the entire code or just the bottom part?

maiden fable
#

Just the bottom

alpine pewter
#
            for player in response["data"]["players"]:
                if player["online"] == True:
                    output_str_a = player["name"]

                    channel = bot.get_channel(channel.id)
                    embed = nextcord.Embed(description=output_str_a)
                    await channel.send(embed=embed)
slate swan
stiff fern
#

I did msg.startswith but it said it needed content or something

maiden fable
slate swan
maiden fable
#

Fill in the dict keys please

slate swan
#

the gateway is meant just to recieve events

slate swan
alpine pewter
# maiden fable Fill in the dict keys please
            for player in response["data"]["players"]:
                if player["online"] == True:
                    output_str_a = player["name"]

                    channel = bot.get_channel(channel.id)
                    await channel.send(", ".join(player for player in response["data"]["players"] if player["online"])) 

Like so?

paper sluice
#

no

#

replace all that with that one liner

alpine pewter
#

Lmao, I forgot the top part, one sec.

#

Thank you

#

Okay, let me test it brb

maiden fable
#

works?

#

@alpine pewter

alpine pewter
#

Yep, got it to work πŸ˜„
Thank you ^^

#

Sorry, just messing with the embed

maiden fable
#

Nice

sullen pewter
#

How can I make this in python

#

I need it to save user data

#

and send them in a channel

#

and delete this data after the message was sent already

robust fulcrum
#

Guys how can we display in how many servers our bot is on website?

maiden fable
#

!d discord.Client.guilds

unkempt canyonBOT
maiden fable
unkempt canyonBOT
robust fulcrum
#

What do I ahve to do for it?

robust fulcrum
slate swan
#

with raw html no, you would have to make requests to the api to get server list payload, since server count data is dynamic

slate swan
#

Discord ofcourse

robust fulcrum
#

Or i need to make my own api?

slate swan
#

How can I set_image as a gif?

#

just like you would do for a normal image

robust fulcrum
#

Do like image

#

Like poop.gif

#

Just put it there

slate swan
robust fulcrum
slate swan
#

if its tenor, you are definately doing it wrong

#

I'm using an api

#

what api is it

robust fulcrum
#

Pokemon?

slate swan
robust fulcrum
#

@slate swan will you help me do the website thing pls?

slate swan
robust fulcrum
slate swan
#

embed.set_image(url="https://api.popcat.xyz/pet?image={}".format(replace)) I tried this.

gaunt herald
#

anyone know how to make mass ping detection?

slate swan
#

Bruh 😢

slate swan
unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
visual island
slate swan
robust fulcrum
#

But i want to display my bot guilds on my website but don't know how to

slate swan
#

or does the api do that, lemme check

#

the api makes it into a gif

#

on the site it shows as a gif

#

im assuming thats because of the .png extension

#

try reading the response from the website and using those bytes for set_image

#

How would I do that

#

!local-file

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

slate swan
#

with req how?

slate swan
#

Does discord just not embed it correctly

#

Even the example doesn't embed as gif in discord

#

https://api.popcat.xyz/pet?image=https://cdn.popcat.xyz/avatar.png
the example the API provides.

#

can you try to figure it out? @slate swan

maiden fable
#

What happened @slate swan

slate swan
maiden fable
#

Show code

slate swan
#

all of it?

maiden fable
#

The embed code

slate swan
#
embed = discord.Embed(title=f"Pet!", color=discord.Color.blue())
  av = str(user.avatar_url)
  replace = av.replace("webp", "png")
  embed.set_image(url="https://api.popcat.xyz/pet?image={}".format(replace))
  await ctx.send(embed=embed)
#

on browser it's a gif but on discord it'snot

maiden fable
#

And paste the url here

#

With `

slate swan
#

https://api.popcat.xyz/pet?image=https://cdn.discordapp.com/avatars/869395298626187324/be6b9bf19f34ddca6f0e092ef78d2be5.png

maiden fable
#

BTW why you using a third party API to get the avatar url

slate swan
#

I'm not?

shrewd apex
#

u want to set user avatar image in set_image?

slate swan
shrewd apex
#

u can just do embed.set_image(url=user.avatar.url)

maiden fable
#

Yea

slate swan
shrewd apex
unkempt canyonBOT
#

Hey @valid panther!

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

shrewd apex
#

wut is final url

valid panther
maiden fable
shrewd apex
slate swan
maiden fable
slate swan
#

if you don't have a discord default avatar*

shrewd apex
#

as they keep changing

slate swan
#

a modem has one single ip

shrewd apex
slate swan
#

no.

maiden fable
shrewd apex
#

ur modem assigns u a ip on ipv4 which u give for public ip or access ip in mongo

maiden fable
shrewd apex
#

u can set a static IP by contacting ur provider tho

slate swan
#

^

#

custom IPs exist, but fine, they do change on restart

maiden fable
shrewd apex
#

ipv4 u would prolly need to pay ipv6 u can get for free

shrewd apex
maiden fable
#

Indeed

#

BTW there's a button in Atlas Mongo. It will add yr current IP to the whitelist

#

U might want to use that

shrewd apex
#

lmao u can just add 0.0.0.0

maiden fable
#

What does that do?

#

Opens to everyone?

shrewd apex
#

that will give access to db regardless ip

magic pond
#

how to send like this

maiden fable
#

Ah, never knew

shrewd apex
#

as long as u have correct password and stuff

maiden fable
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
maiden fable
shrewd apex
#

ik rightπŸ˜‚

maiden fable
#

Happened with me once. Caps vs cAPS

shrewd apex
#

mongo is pretty good would be better if it were free atleast more than one cluster per project

shrewd apex
maiden fable
maiden fable
#

I hate it when that happens

shrewd apex
#

lmao it took me a long time to realise

maiden fable
#

U press the key but it doesn't get presses properly

shrewd apex
#

yeah like sometimes i click caps on shift or tab

slate swan
#

What's the topic going onpithink

maiden fable
#

BTW did u know u can show movie trailers on yr Rich Presence 🀣

#

Infinity Wars trailer was running on mine yesterday

shrewd apex
#

oh what's today end game?

maiden fable
#

(Ignore the presence name)

slate swan
maiden fable
#

That's iron man

maiden fable
slate swan
#

how?

maiden fable
#

Also self bots and bots can't have pics in their presence

maiden fable
unkempt canyonBOT
shrewd apex
#

i need to watch multiverse of madness

slate swan
shrewd apex
#

but online quality is bad

shrewd apex
maiden fable
slate swan
shrewd apex
#

OoO

#

that bad?

slate swan
robust fulcrum
#

Guys how can we make !eval command like @unkempt canyon
Me not able to understand from its GitHub repo

maiden fable
#

!d exec

unkempt canyonBOT
#

exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
robust fulcrum
#

Idk how to make it :(

slate swan
shrewd apex
#

exec is like Superman of python

slate swan
#

os.remove()

#

imagine on bot

#

iirc there is something like jish

shrewd apex
#

thats why have to use a sandbox environment for stuff like this

shrewd apex
slate swan
unkempt canyonBOT
slate swan
#

Ye that

shrewd apex
desert cosmos
#

yeah what does different libraries do i use py-cord and i don't think i need to change
but it would be great to learn about others too

shrewd apex
#

same thing in different way i suppose never used others from what i remember there is pycord nextcord hikari

desert cosmos
#

disnake also ig

slate swan
# shrewd apex what does this do?

just adds more commands to your bot, like, music and async running of python code with some more features for the discord library too

robust fulcrum
shrewd apex
maiden fable
desert cosmos
#

i don't know if lavalink lags because of replit or some code irregularities

slate swan
slate swan
desert cosmos
#

although it only lags at specific time of the day

robust fulcrum
#

How can we make eval command can anyone tell pls?

maiden fable
desert cosmos
slate swan
maiden fable
#

Ngl jsk is good, but it doesn't let the person learn since u don't learn how to make diff commands like debug and eval, among others

honest laurel
shrewd apex
#

add ur ip to ur network access area in atlas

maiden fable
maiden fable
#

Uh?

honest laurel
#

You need a debugger πŸ™‚

#

not eval

slate swan
shrewd apex
robust fulcrum
slate swan
shrewd apex
#

idk how he wants it i told the classic how to solve it

slate swan
maiden fable
# honest laurel not `eval`

I don't think u will want to open the VPS and do changes directly to the deployed bot code, in order to debug. Since eval only does the changes in cache and not in real files, it's safe to use it if u r debugging an already deployed bot

robust fulcrum
honest laurel
shrewd apex
maiden fable
slate swan
#

why not this πŸ˜”

#

nvm

honest laurel
#

For example?

shrewd apex
#

whatsmyip does the samepithink and i don't need to type...

shrewd apex
maiden fable
# honest laurel For example?

My bot resets the data for some servers randomly but this issue wasn't present while I was deving the bot since it's an edge case one. I was able to solve it using eval since I was able to see what is the value of some variable at a given point of time. This way I was able to figure out the issue without too much downtime and debug prints directly in the code

honest laurel
robust fulcrum
slate swan
#

Asher will help

shrewd apex
#

2.0 i think he has...

shrewd apex
honest laurel
shrewd apex
#

yeah u can

robust fulcrum
robust fulcrum
#

Jishaku confusion!

cloud dawn
shrewd apex
shrewd apex
honest laurel
#

I usually run it like this:

async def create_bot() -> commands.Bot:
    intents = discord.Intents.default()
    intents.message_content = True
    intents.members = True

    bot = commands.Bot(
        command_prefix=settings.bot.prefix,
        intents=intents,
    )

    return bot
async def main() -> None:
    import app
    import settings

    bot = await app.create_bot()
    async with bot:
        await bot.start(token=settings.bot.token)


if __name__ == "__main__":
    dotenv.load_dotenv()
    asyncio.run(main())
robust fulcrum
cloud dawn
honest laurel
honest laurel
cloud dawn
#

Okay then why not ```py
intents = discord.Intents.all()
intents.presences = False

shrewd apex
#

correct me if i am wrong but isnt load_extension now async so all cogs loading have to be async?

honest laurel
shrewd apex
#

like

await bot.load_extension('')
honest laurel
#

load_extension and add_cog are async now

cloud dawn
shrewd apex
honest laurel
shrewd apex
#

yeah

shrewd apex
#
#1.7.3 was
bot.add_cog(Greetings(bot))
#2.0 is
await bot.add_cog(Greetings(bot))
honest laurel
#

cogs were async, if you're talking about add_cog method then say add_cog method πŸ˜…

#

But yep, these two methods were sync

shrewd apex
#

thats what i meant

honest laurel
#

so all cogs LOADING have to be async - I can't read sometimes

slate swan
#

no

#

only for v2

shrewd apex
slate swan
#

you could make them synced too if you monkey patch dpy

shrewd apex
honest laurel
honest laurel
slate swan
honest laurel
#

Because it's easier

shrewd apex
#

is creating or declaring bot instance without subclass bad?pithink

cloud dawn
#

I mean he isn't really adding anything to Bot so subclass is a bit over the top.

honest laurel
#

@slate swan Where would you load extensions and cogs then?

shrewd apex
#

so why not just do bot=commands.Bot isnt that easier?

slate swan
shrewd apex
#

yeah true

honest laurel
#

What kind of functions?

shrewd apex
#

but i dont require them much so i dont

#

at max i only need one or two db connections

slate swan
slate swan
shrewd apex
#

yeah

cloud dawn
#

I do loads of things inside the subclass Bot.

shrewd apex
#

but sub classing does make the code look cooler and more structured

shrewd apex
honest laurel
cloud dawn
# shrewd apex like?

Database, loading Groups, syncing, custom close function for http client, start-up datetime object and getch functions.

honest laurel
#

Yeah, in this case subclassing it is better

robust fulcrum
#

Can anyone tell how can I use jishaku?
Not able to understand it

robust fulcrum
shrewd apex
#

idrk never used i have to read the docs...

robust fulcrum
#

It's docs is very hard

slate swan
shrewd apex
robust fulcrum
#

Ig me should see more python videos from youtube

honest laurel
honest laurel
#

env variables

robust fulcrum
#

Hmm hey ash can you tell where I have to load extension?

slate swan
honest laurel
#

For example you can use pydantic

class BotSettings(BaseSettings):
    class Config:
        env_prefix = "bot_"

    prefix: str = "!"
    token: str
slate swan
#

i'll be fine

honest laurel
#

I don't think you should store all of this in your bot, that's all

robust fulcrum
#

Can we make eval command without jishaku?

#

Is there any other way?

shrewd apex
#

whats diff between os.environ and os.getenv?

honest laurel
slate swan
honest laurel
slate swan
slate swan
shrewd apex
#

oh just asked i use os.environ to get tokens... so

#

where do u guys host your bot?

honest laurel
#

What could you recommend to ensure that a user has an account in db before executing a command?
I'm currently using something like this:

async def ensure_account(session: AsyncSession, user: Member) -> Account:
    account: Account | None = await session.get(Account, user.id)
    if account is None:
        account = Account(id=user.id)
        session.add(account)
    return account
honest laurel
slate swan
slate swan
robust fulcrum
#

Hmm pls tell how can I make eval command without jishaku

shrewd apex
#

like a few microseconds

slate swan
#

whatever suits

shrewd apex
#

btw u guys know any good examples for selection drops the ones in the docs arent so good?

honest laurel
#

__bool__ method could be overridden, so it's better to use is None if you're checking for none specifically
Otherwise code like this might not work properly:

def example(number: int | None):
    if not number:
        ...
slate swan
#

hm interesting

honest laurel
#

There are some cases when you need to do something like this:

_unset = object()

def example(number: int | None = _unset):
    if number is _unset:
        ...
slate swan
# shrewd apex btw u guys know any good examples for selection drops the ones in the docs arent...
import discord
from discord.ext import commands
from discord import ui

class BaseDropDown(ui.Select):
  def __init__(self):
    select_values = [
  discord.SelectOption(label = "Yes", description = "Choose Yes."),
  discord.SelectOption(label = "No", description = "Choose No.")]

    super().__init__(placeholder="Confirm", max_values=1, min_values=1, options=select_values)
   
  async def callback(self):
    await interaction.response.send(f"You chose {self.values[0]}") #values is inherited from Select and is a list of options that were selected from the dropdown

class DropDown(ui.View):
  def __init__(self):
     super().__init__()
     self.add_item(BaseDropDown())

@Bot.command()
async def _(ctx: Context):
  await ctx.send("uwu", view=DropDown())
regal pulsar
#

i use if not way too often

honest laurel
shrewd apex
slate swan
# shrewd apex thx lemme have a look❀️

welcome, just on a side note, if you dont want to subclass View to add the drop down, you could simply instantiate it in a variable using view = ui.View() and view.add_item(BaseDropDown()) in that case, and you could add a timeout if necessary in the View class's initiator function

regal pulsar
#
import discord
from discord.ext import commands
from discord.ui import Select, View
from discord import SelectOption as OP

async def callback(inter):
    pass

@bot.slash_command()
async def test(inter):
    select = Select(options=[OP(), OP()], callback=callback)
    view = View()
    view.add_item(select)
    await inter.response.send_message(view=view)
slate swan
#

slash command

regal pulsar
#

without subclassing

regal pulsar
#

true

#

but i prefer this

honest laurel
shrewd apex
slate swan
regal pulsar
#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
slate swan
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
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.
regal pulsar
shrewd apex
#

ok cool so in the interaction embed if i add buttons and have the same selection drop user will be able to shuttle thru embeds here right? buttons are for pagination btw

regal pulsar
#

wait can you have multiple ui items in one message

honest laurel
shrewd apex
#

it's like i have 3 category under which category i have a few embed with pagination

shrewd apex
regal pulsar
#

yes

honest laurel
#

Yep

shrewd apex
slate swan
#

just make a SelectMenu object then add it in the same view which subclasses View and add the dropdown object in that View class

#

and the buttons

shrewd apex
#

yeah cool thx a lot again

slate swan
#

welcome, I'll go to sleep now, good night

shrewd apex
#

gn sweet dreams

robust fulcrum
#

Guys can anyone pls help
Can we make eval command without jishaku