#discord-bots

1 messages · Page 954 of 1

jolly karma
#

yea

#

only thing my bot does is

#

joins a vc for 24/7

#

and plays rick roll

slate swan
#

ahh simple

jolly karma
#

lmao as a joke in my smol server

slate swan
#

whatd u do name it rick roll vc

jolly karma
#

nah

#

i just named the vc "dont join 🗿 "

#

lol

#

i can do anyting thats funny

#

(not crimes or something that hurts others) 😇

slate swan
#

true thing

slate swan
#

yui?

jolly karma
jolly karma
#

idk

#

btw how do i loop the audio (3+1)ever

#

like i just use a loop?

#

😳

#

?

slate swan
#

yeah a loop

#

or a while loop

verbal breach
#

I learnd that rate limits exist……

#

uhhhhh…….

slate swan
#
while True:
    print("hello world") # whatever u want to loop forever

@jolly karma

slate swan
#

i need some help, lets say this is my code, so my question is if i call the function, does it automatically go through the function and then come back to the code below?

embed = discord.Embed(title="test")
await ctx.send(embed=embed)
async def function()
embed2 = discord.Embed(title="test2")
await ctx.send(embed=embed2)
verbal breach
#

but like……how do i avoid this in the future

slate swan
slate swan
slate swan
jolly karma
slate swan
#

which one is it?

#

why don't you just test it..

#

yea im actually testing it rn lol

jolly karma
#
import discord
from discord.ext import commands
import time
from keep_alive import keep_alive
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())

@bot.event
async def on_ready():
  print("online uwu")
  await bot.change_presence(activity=discord.Game(name="Altera")) 
  channel = bot.get_channel(959704295903748137)
  if not channel:
    return
  try:
    await channel.connect()
    vc.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source="./rick_roll.mp3"))
  except discord.Forbidden:
    print("Gimme perms")
keep_alive()
bot.run
``` @slate swan its not working ;-;
slate swan
#

ok it worked

slate swan
#

good

slate swan
#

don't forget to add the token when you try running it

jolly karma
jolly karma
verbal breach
#

btw can i do something like

if message.author == client.”Username”:
  await message.channel.send(‘some text’)
slate swan
#

why would you wanna do that

verbal breach
#

no specific reason. I just want to know.

#

also how can i use my bot and test it if it never will read my messages

slate swan
#

I mean yeah kinda, you probaby need to specify the discord id of user but yes

#

he doesnt

slate swan
#

can I see your previous code?

verbal breach
#

no im saying in discord. My messages will never be read by it. It said that your messages wont affect it when i was creating new bot

slate swan
#
if message.author == user#0001:
  await message.channel.send(‘some text’)
slate swan
#

that will work

slate swan
jolly karma
slate swan
slate swan
slate swan
slate swan
#

oh they forgot to install it

jolly karma
slate swan
#

and ugh, dont do stuff in on_ready

jolly karma
slate swan
#

replit smh

slate swan
#

8th line is on_ready..

azure scroll
#
    @commands.command()
    async def timer(self, ctx, time_h, time_m, time_s):
        time_h = int(time_h)
        time_m = int(time_m)
        time_s = int(time_s)
        now = datetime.timezone.utc
        future = now + datetime.timedelta(hours=time_h, minutes=time_m, seconds=time_s)
        await discord.utils.sleep_until(future)
        await ctx.send(f"{ctx.author.mention} your time is up")

Error:

TypeError: unsupported operand type(s) for +: 'datetime.timezone' and 'datetime.timedelta'```
slate swan
jolly karma
jolly karma
jolly karma
#

breh dont know python much

azure scroll
#

like how do i fix it

#

?

slate swan
# jolly karma i literally did nothing ;-;
async def on_ready():
  print("online uwu")
  await bot.change_presence(activity=discord.Game(name="Altera")) 
  channel = bot.get_channel(959704295903748137)
  if not channel:
    return
  try:
    await channel.connect()

nice nothing u got here

slate swan
#

just make it print online, and then make a seperate command for it

slate swan
#

thats how you get blocked from discord api

#

no...

slate swan
jolly karma
azure scroll
slate swan
#

im pretty sure i got blocked, cause whenever i started my bot there was a cloudflare error saying ive been blocked/banned

#

it would be better to check if your bot is in the channel, playing or not, every 6 hours or so, so use a task

supple thorn
#

Just glanced at the channel

slate swan
#

💀

#

seems like it would be

slate swan
#

yall really dissing ash💀

slate swan
slate swan
supple thorn
#

It's to add uwu to stuff

slate swan
#

but I dont do things in on_ready 😔

#

anyways i think im just gonna dip from the chat all i see is on ready requests and attr errors and other cursed stuff

snow ibex
#

purpur

slate swan
jolly karma
snow ibex
#

we copy

supple thorn
boreal ravine
jolly karma
slate swan
#

or just code local if you are going to self-host it in the end

jolly karma
#

i am just tesing my bot there;-;

snow ibex
#

fuck wronng hog

slate swan
supple thorn
#

Looks like a bear with a coat

slate swan
snow ibex
#

🐗

supple thorn
#

Lmao hedgehog

jolly karma
slate swan
snow ibex
slate swan
supple thorn
#

Back to messing with flask and fastapi

slate swan
snow ibex
boreal ravine
#

!ot

unkempt canyonBOT
jolly karma
slate swan
supple thorn
boreal ravine
#

stop going offtopic for fucks sake

slate swan
supple thorn
#

And see what i prefer

slate swan
supple thorn
#

Must have something good if it's named fastapi

jolly karma
supple thorn
#

😔

slate swan
supple thorn
#

Ah

#

This is why i saw alot of biased posts about fastapi

slate swan
#

it really depends its just like
django vs flask vs fastapi

#

i personally like flask more

supple thorn
#

Okay

slate swan
#
from discord.ext import tasks, commands

uwu_bot = commands.Bot(command_prefix="whatever", intents=discord.Intents.default())

@uwu_bot.event
async def on_ready():
  print("online")

@tasks.loop(hours=3)
async def music_task():
  await uwu_bot.wait_until_ready()
  channel = uwu_bot.get_channel(959704295903748137)
  if not channel:
    return
  try:
    await channel.connect()
    vc.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source="./rick_roll.mp3"))
  except discord.Forbidden:
    print("Gimme perms")
music_task.start()
uwu_bot.run()
supple thorn
#

My next problem after learning flask is how to publicly host a API

#

I have a vps but don't know how to do that shit for now

slate swan
slate swan
supple thorn
slate swan
#

anyways goodnight its 3am and im gonna go to sleepAG_MochaThumbsUp

slate swan
slate swan
supple thorn
slate swan
#

ugh

supple thorn
slate swan
light violet
slate swan
supple thorn
supple thorn
slate swan
#

slowworksonmymachine

light violet
#

I defined member still not working help pls guyz

slate swan
#

not the problem.

#

the problem is the class doesnt have that attr hence why we gave avatar with a url attr since avatar returns an asset iirc

placid skiff
#

the problem is replit D_D

slate swan
#

nah

placid skiff
#

yup

slate swan
#

no

#

leave replit alone😔

slate swan
supple thorn
#

Always think about rins models

#

Ashley comes with the uwu package

slate swan
#

the bot probably got disconnected from the gateway

slate swan
slate swan
boreal ravine
#
  • the bot went offline
  • your internet is shit
slate swan
#

lmao

#

sift you slow bro

#

im so fast no one realizes how fast i amfingerWave

boreal ravine
#

maybe you didn't defer the interaction.

slate swan
#

you were seeing it 24 hours a day?

#

and the bot never gets offline as soon as its disconnected

boreal ravine
#

have you considered making the view persistent?

supple thorn
slate swan
supple thorn
#

Time to eat hard water

slate swan
#

a view bound to your bot

boreal ravine
slate swan
#

quite cool

somber sky
#

does anyone know how long it takes for repl.it to unblock u from website or is it just random

somber sky
#

GOD DAMN

slate swan
#

at least that was for me

somber sky
#

hell nah what other websites is there

#

replit is shit

slate swan
somber sky
#

what does is do

slate swan
somber sky
#

oh ok

slate swan
slate swan
#

it depends on the api and you could just change your ip because youre just being ratelimited by cloudfare to your ip

somber sky
slate swan
#

i think ash hates me for correcting her all day😭

slate swan
somber sky
slate swan
#

oof

slate swan
#

i said the something and you just said the same thing

slate swan
#

doubt

somber sky
slate swan
#

only person i correct to make them hate me is water_gazes because hes my bro😔

junior verge
#

whats the import for utils.util

maiden fable
formal basin
maiden fable
#

...?

formal basin
junior verge
#

I mean, how do I install it? I am confused

maiden fable
formal basin
junior verge
#

Yeah

maiden fable
junior verge
#

But in my file it even shows it like this btw

formal basin
maiden fable
#

Okay

junior verge
#
matplotlib==3.5.1
matplotlib-inline==0.1.3
mpmath==1.2.1
numpy==1.22.0
py==1.11.0
requests==2.27.1
discord==1.7.3
discord.py==1.7.3
aiohttp==3.7.4
async-timeout==3.0.1
discordmongopy==0.3.0
motor==2.5.1
pymongo==3.12.0
python-utils==3.1.0
beautifulsoup4==4.10.0
lxml==4.8.0
wavelink==1.2.4
buttons==0.1.9
slate swan
#

.....?

maiden fable
#

!pypi utils

unkempt canyonBOT
maiden fable
#

!d utils

junior verge
#

oh

#

my bad

azure scroll
#

can someone post an example of sending a simple dm

junior verge
#

I get it

maiden fable
#

@junior verge what module is that

junior verge
#

its from utils

#

no nvm

maiden fable
slate swan
junior verge
#

Still says this

maiden fable
#

Which module...

junior verge
#

I am not sure actually

slate swan
#

....

#

why isnt this getting ratelimited 😔

quick gust
#

u forgot to copy his utils folder

maiden fable
slate swan
#

random 8 am thoughts

junior verge
junior verge
maiden fable
# slate swan bored

And make replit worse for other people who tryna host their bots on it without getting ratelimited? Not good

primal cradle
#

hey i found an opensource discord.py based bot, and while i'm decently skilled with python i cant for the life of me get this working

#

anyone have tons of time to kill and willing to utterly waste it with me pls?

maiden fable
#

Ashley is getting bored 👀

slate swan
#

so doing any logical stuffs is way out of my head

formal basin
lament mesa
slate swan
formal basin
slate swan
lament mesa
#

oh lol

formal basin
slate swan
slate swan
#

..

supple thorn
primal cradle
#

guy made it for himself and then just posted it bc why not

#

it calls on alot of directories and .json files that simply dont exist

#

also a module that pip cant download

supple thorn
supple thorn
primal cradle
#

i would learn python and actually become competent at this but python is the worst language to learn rn

primal cradle
supple thorn
#

Curious on what the hell you're copying

slate swan
primal cradle
primal cradle
supple thorn
primal cradle
slate swan
# supple thorn Discord likes you

I swear it doesnt, I literally put my phone away, started eating, my watch vibrated, and I got a notification from my bot, saying uwu, uwu backfiring 😔

primal cradle
#

actually no im too lazy to fully type this out

slate swan
#

too smart smh

supple thorn
#

Imagine checking your smart watch and seeing uwu

#

At that point i'd think it was hacked

primal cradle
#

tldr; interpreted, inheritance, ultra high level, dosent actually teach you shit about base level computing, every school in america is teaching python rn the market is gonna be so saturated in 5 years omfg

slate swan
supple thorn
primal cradle
#

gonna setup a banking system

supple thorn
#

So just need a basic understanding of how to make a bot and an understanding of a database

primal cradle
supple thorn
slate swan
supple thorn
#

It is quite alive

slate swan
#

still

primal cradle
#

wasnt it deprecated

slate swan
#

no

slate swan
supple thorn
#

In a span of 6 months

slate swan
#

you mean Facebook

#

yes

#

😳

#

well....facebook is owned by meta, so same thing

#

its used by allot of companies but people say python is slow because its interpreted when its not really even a bad thing while in a compiled language you encounter an error and everything crashes

supple thorn
#

Is a lot actually spelled allot

slate swan
#

and its not even slow its slower than other langs but you cant even feel the difference

slate swan
slate swan
glad cradle
#
from disnake.ext import components
disnake.ext.commands.errors.ExtensionFailed: Extension 'slashCommands.test' raised an error: ImportError: cannot import name 'components' from 'disnake.ext' (unknown location)
#

i need to use @components.component_listener()

supple thorn
slate swan
#

anyways im going to sleep goodnight!AG_RinSleep

slate swan
slate swan
supple thorn
#

Okimii just wakes up in the middle of sleeping if he feels the force is unbalanced here

slate swan
#

yes i feel the cap in this channel

#

The Force 😔

#

everytime i feel that negative force i come here and im never surprised

supple thorn
#

Just springs back to awake mode

slate swan
#

still thinking on rins models😔

supple thorn
#

Okimii seems like that kid whom is always online

slate swan
#

i am

supple thorn
#

You just gotta know the secret phrase

slate swan
#

.

#

i have no life no friends only thing i do is procrastinate snuggle

#

do you guys even go outside-

#

only when i have to go to schoolAG_WorrySadge

supple thorn
#

Well i should really say months

slate swan
#

no comments

#

i feel like something bad is gonna happenAG_ChikaScared

supple thorn
#

I last went outside in december for christmas

#

So like 5 months?

slate swan
#

bro

#

....

#

4 months and 10 days

supple thorn
#

Atleast it got decreased by a month

slate swan
#

4 months and 8 days I mean

supple thorn
#

I haven't touched grass in over 2 years

slate swan
#

anyways im actually going to sleep because im tired peepocomfy

#

cool

supple thorn
#

There's mostly no grass here

#

I'm not in africa

slate swan
#

who would assume that

supple thorn
#

I did

slate swan
#

lmao

supple thorn
#

First thing to pop in my head

slate swan
#

wonder no one asked us to go to an ot channel

#

me rnAG_Smirk

boreal ravine
supple thorn
boreal ravine
#

all guilds are cached on startup

supple thorn
#

I utilize this time frame to talk normally

slate swan
slate swan
supple thorn
#

I'ma go eat crisps

slate swan
#

but yes all guilds get cached when the GUILD_CREATE gateway event is dispatched

slate swan
#

not very appropriate AG_ChikaStunned

supple thorn
#

Ashley very lonely

slate swan
#

btw messages get logged

#

its fine

#

😉

#

with

#

define didnt work

#

Defer the commad.

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
spice basalt
#

how can i make the embed's color the user's top role color?

slate swan
#

show full error

spice basalt
slate swan
#

show full error!!!

spice basalt
#

that's the full error 🗿

slate swan
#

n

spice basalt
#

that's all, stop ghost pinging me

slate swan
#

ok

unkempt canyonBOT
#

Hey @spice basalt!

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

spice basalt
#

see?

#

i'm not sure if you even know what i want

vale wing
slate swan
#

..

spice basalt
slate swan
#

yes so the error would be attributeerror: 'Nonetype' object has no attribute 'color'

paper sluice
#

how do u get the slas commands in dpy 2.0

snow ibex
#

Null check member

spice basalt
slate swan
#

1st u didnt show the full error

spice basalt
#

are you stupid

slate swan
#

it didnt show None

spice basalt
snow ibex
spice basalt
snow ibex
#

Works wonders

#

if member == none:
member = ctx.author

slate swan
#

wait ill share what i use

snow ibex
spice basalt
slate swan
#
async def di(self , ctx , user: disnake.Member=None):
      user = ctx.author if not user else user
spice basalt
snow ibex
#

Ah

#

I see what you want to do now

spice basalt
#

yes

snow ibex
#

Maybe make a string instead

spice basalt
#

by that you mean?

snow ibex
#
name= ""
if member == None:
    name = "You are"
else: 
  #name = member.displayname 
#

Some thing like that

#

Oh yeah that's litterally what you did

slate swan
#

?

spice basalt
#

sparky what are you trying to do

slate swan
#

Helping you :)

snow ibex
#

The color thing could be done using the same if statement

spice basalt
#

helping me how

slate swan
snow ibex
#

Stupid way of doing it but

if member == None:
    color=ctx.author.color
else:

slate swan
snow ibex
#

Hm

slate swan
#

!e

print(0 == False, 0 is False)
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
slate swan
#

in this case member can be literal to the NoneType class so just compare entities

spice basalt
#

that would make the color the author's color and the author's color only

slate swan
#

nah

spice basalt
#

it won't change to someone else's color if you mention someone else

slate swan
#

only if the condition is true

spice basalt
#

ah

slate swan
spice basalt
#

yes

slate swan
#

the variable as the one that can have the argument or the author

somber sky
#

anyone know how to do this? im trying to make it where after u set the transactionchannel every time you run the test command it sends to the transactionschannel

slate swan
#

if you want to make it per user just use a db and store the channel id

somber sky
#

its for each server

#

its like that. once i set it everytime i run the command regardless what channel i do it in it will always send it to the transaction channel

#

if i ran the command in general it would just send it to the transaction channel

#

and yes ik i could just do channel = bot.get_channel(ID) but im trying to sell it and give away so i dont wanna be putting id's

#

i want it to be set to what they want

slate swan
#

It says arrow is not defined, any ideas on how to define it?py bot_ping = (arrow.utcnow() - ctx.message.created_at).total_seconds() * 1000

supple thorn
#

Are you perhaps wanting datetime.utcnow()?

supple thorn
#

!d discord.ext.commands.Bot.latency

unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
slate swan
supple thorn
#

Also what the fuck is arrow

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can't subtract offset-naive and offset-aware datetimes <- thats using datetime

pliant gulch
#

You could then subtract using created_at

slate swan
#

ohh alright, thanks

#

'function' object has no attribute 'utc'..

pliant gulch
slate swan
#

okay

#

says datetime.datetime has no attribute 'timezone'

#

wait

supple thorn
#

A lot of errors when you could just use the latency attribute

slate swan
#

i know but im trying to make an advanced one

supple thorn
#
from datetime import timezone
slate swan
#

okay

supple thorn
#

I was goddamn called mid type

#

🗿

slate swan
#

fixed it, thanks for the help 💜

hasty stump
#

how can i make a command where people can upload pic with text
like, ?add Test (and a pic/file)
it will sent a embed where description will be Test and at down image/file.

supple thorn
#

I'm so damn confused

#

Are you telling yourself

#

That message has a embeds attribute

somber sky
#
@slash.slash(description='Setup Tickets')
async def ticketsetup(ctx, channel: discord.TextChannel):
  ticket = discord.Embed(title='Tickets', description=f'Have any problems?\n\n If you are having problems in SFL please create a ticket below so our moderation team can assist you.\n\n **Reminders:**\n > • Troll tickets will not be tolerated, doing so could get you Muted, Kicked and possibly banned.\n > • Disrespecting staff will get you Muted and possibly banned as we are trying our best to assist you.')

  ticket.set_thumbnail(url=f"{ctx.guild.icon_url}")

  ticket.set_footer(icon_url = bot.user.avatar_url, text='{}'.format(ctx.bot.user))

  components = [
    Select(
        placeholder = 'SelectMenu',
        options = [
            SelectOption(label="SelectMenu1", value="value1"),
            SelectOption(label="SelectMenu2", value="value2"),
            SelectOption(label="SelectMenu3", value="value3"),
            SelectOption(label = "SelectMenu4", value = "value4"),
            SelectOption(label="SelectMenu5", value="value5"),
            SelectOption(label="SelectMenu6", value="value6"),
            SelectOption(label = "SelectMenu7", value = "value7"),
            SelectOption(label = "SelectMenu8", value = "value8")
            ])]
  
  await channel.send(embed=ticket)``` im tryna figure our how to add the selectoption to the embed
supple thorn
#

Oh i thought there was a yerlikaya imposter there

supple thorn
slate swan
#

whats error ??

supple thorn
supple thorn
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 to fix that ?

somber sky
#

you need to show the code u put to many tabs

#

or u didnt put enough

heavy folio
#

your fault

#

common sense to know the lib before even helping

slate swan
slate swan
supple thorn
#

That's ah

#

Very clear indentation

#

Well atleast i'm in disnake

slate swan
#

I agree, the amount of pride complexity certain people have is just way too much to say about their character ngl

hasty stump
slate swan
#

you dont need no parameters for an attachment input

somber sky
#
@slash.slash(description='Setup Tickets')
async def ticketsetup(ctx, channel: discord.TextChannel):
  ticket = discord.Embed(title='Tickets', description=f'Have any problems?\n\n If you are having problems in SFL please create a ticket below so our moderation team can assist you.\n\n **Reminders:**\n > • Troll tickets will not be tolerated, doing so could get you Muted, Kicked and possibly banned.\n > • Disrespecting staff will get you Muted and possibly banned as we are trying our best to assist you.')

  ticket.set_thumbnail(url=f"{ctx.guild.icon_url}")

  ticket.set_footer(icon_url = bot.user.avatar_url, text='{}'.format(ctx.bot.user))

#how do i add this to the embed?
  components = [
    Select(
        placeholder = 'SelectMenu',
        options = [
            SelectOption(label="SelectMenu1", value="value1"),
            SelectOption(label="SelectMenu2", value="value2"),
            SelectOption(label="SelectMenu3", value="value3"),
            SelectOption(label = "SelectMenu4", value = "value4"),
            SelectOption(label="SelectMenu5", value="value5"),
            SelectOption(label="SelectMenu6", value="value6"),
            SelectOption(label = "SelectMenu7", value = "value7"),
            SelectOption(label = "SelectMenu8", value = "value8")
            ])]
  
  await channel.send(embed=ticket)```
hasty stump
slate swan
#

yeah, the first ones to act up like they know too much and the last ones to even know what etiquettes are 😔

slate swan
hasty stump
#

i am confused

hasty stump
slate swan
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Embed.Empty "nextcord.Embed.Empty") removes the image.
slate swan
#

sad to see disnake is still better than nextcord

slate swan
hasty stump
slate swan
#

..

slate swan
#

he wants to send a file in a embed

#

or she

slate swan
# hasty stump i still didnt understood

make/get an instance of an Embed object and use the set_image method on it and do

embedins.set_image(url="attachment://uwu.png")

make sure that embed's set_image in nextcord does not support full paths and need to be in the same dir

placid skiff
#

did you broke discord formatting? D_D

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

its a png

#

plus its being used in a file kwarg in the embed constructor

#

which isnt a thing

#

then again the path is not a string

somber sky
#

does anyone know how to make it where a certain person can run the command

#

like the id

slate swan
#
def validate():
     async def predicate(ctx):
           if ctx.author.id in (id1, id2):
                  await ctx.send
                  return True
            return False
      commands.check(predicate)

@validate

hasty stump
#

why is this error

slate swan
#

because its sending the Cog

placid skiff
#

imagine naming a class and a method with the same name

hasty stump
#

is that the issue?

slate swan
#

why imagine when you can do it

placid skiff
slate swan
placid skiff
hasty stump
#

if u dont want to help then stay quiet.

slate swan
#

can we not

placid skiff
#

yup but basic python and OOP knowledge is required to use d.py or any OOP based package

slate swan
#

please?

hasty stump
slate swan
hasty stump
#

@slate swan can u now tell me how can i sent a image with this

maiden fable
#

U want to set the image in the embed?

#

!d discord.Embed.set_image @hasty stump

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
hasty stump
#

image/file/link

maiden fable
#

Use set_image

hasty stump
slate swan
hasty stump
slate swan
# hasty stump

an asterisk is used to define tgat the next parameters would be keyword arguments

hasty stump
#

i was was rechecking the whole code and got it

slate swan
#

!kwargs

unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
Decorators (see !tags decorators)
Inheritance (overriding methods)
Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

somber sky
#

bro howcome whenever i add a new slash command to my bot i have to re invite him to the server or it takes like 3 hours just for the command to go through

slim ibex
#

set the guild id kwarg in the decorator

devout iris
#

How do I make the message delete function error if there are not enough messages in the channel?

severe acorn
granite parcel
#

async def create_db_pool():
bot.db = await asyncpg.create_pool(database=catchydb,user="postgres", password="test")
print('Connected to db')

bot.loop.create_task(create_db_pool())

#
022-04-04T11:43:36.677830+00:00 app[worker.1]:     bot.loop.create_task(create_db_pool())

2022-04-04T11:43:36.677844+00:00 app[worker.1]: AttributeError: 'Command' object has no attribute 'loop'```
#

?

snow ibex
#

where did you define bot?

maiden fable
#

Seems like u have a command named bot

scarlet aurora
#

how can i make it so that the error message for commands is displayeed differently on the console?

#

how do i define errorclass, i want to make a custom error handlerer

hazy oxide
#

anyone know how to urlopen in urllib3?

flint yew
#

no

hazy oxide
#

cry about it

long blade
#

how can i make the data in the image neat here code ```py
async def open_account(user):
users = await get_bank_data()

if str(user.id) in users:
    return False
else:
    users[str(user.id)] = {}
    users[str(user.id)]["Wallet"] = 0
    users[str(user.id)]["Bank"] = 0

with open("bank.json", 'w') as f:
    json.dump(users, f, indent=4)

return True```
slate swan
boreal ravine
wide thunder
#

oh they answered already

slim ibex
hasty lake
supple thorn
hushed galleon
rocky orchid
#

Any help on how to use an API? I tried looking online but none of the tutorials seem to be what I'm looking for

#

I'm trying to make a command that gives you a random fact

unkempt canyonBOT
rocky orchid
#

Thx!

hushed galleon
#

note that lib reads from a premade text file

#

no issues with blocking requests at least

rocky orchid
#

It says it didn't find a module named "randfacts"

slate swan
#

pip install randfacts

rocky orchid
#

It says it downloaded it, sorry for my stupidity but what do I do now

slate swan
#

How much facts do they have

#

I have no clue

#

..

#

Wym by host it

rocky orchid
# slate swan

I did this, then I got the problem of it saying it didn't find it

rocky orchid
slate swan
rocky orchid
#

how :D

slate swan
#

pip install randfacts==0.14.0

#

@rocky orchid

rocky orchid
#

👍 testing

slate swan
hushed galleon
#

persistent views have to be created and added to the bot on start up using Client.add_view(), and your buttons need to have a custom_id set in the decorator too

rocky orchid
#
  File "main.py", line 3, in <module>
    import randfacts
  File "/home/runner/CaringWrongCryptos/venv/lib/python3.8/site-packages/randfacts/__init__.py", line 46, in <module>
    from randfacts.randfacts import get_fact, safe_facts, unsafe_facts, all_facts
  File "/home/runner/CaringWrongCryptos/venv/lib/python3.8/site-packages/randfacts/randfacts.py", line 7, in <module>
    with open(os.path.join(dir_path, 'safe.txt'), encoding='utf-8') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/.cache/pip/pool/c5/77/41/safe.txt'```
#

I'm doing this in replit

hushed galleon
rocky orchid
slate swan
hushed galleon
#

yeah thats why you set up a persistent view

slate swan
#

Anyone tell him how to create a virtual environment pls

vale wing
vale wing
#

Why are yall even using replit for bots

rocky orchid
#

i dunno

vale wing
#

Youtube?

rocky orchid
#

yes

slate swan
#

Oh

rocky orchid
#

:>

vale wing
#

Setup normal development environment

slate swan
#

Do u have a pc?

slate swan
vale wing
#

Like vsc or pycharm

slate swan
#

@rocky orchid do u have pc

rocky orchid
#

mac

slate swan
#

Good enough

vale wing
#

You can install vsc that's for sure

slate swan
#

Yes

#

Even if its low end doesn't matter

rocky orchid
#

yea i got it installed i was just trying things in replit

vale wing
#

Why not try things in vsc lol

rocky orchid
#

i dunno :P

#

i gotta go

vale wing
#

K cya

#

I remember how I used to code bots on phone that was aids 😳

slate swan
#

Sad

#

Imagine using replit on pc

lone hare
#

can anyone help me

slate swan
#

Sure

lone hare
#

heroku not working

frozen patio
abstract kindle
#

Anyone have an example of slash command from 2.0

#

I can't figure it out with all this tree stuff

frozen patio
hushed galleon
#

im guessing you're using a fork of dpy right

#

my phone loads documentation so slowly :(
but it seems disnake should have the message content intent too

abstract kindle
#

anyone have an example of slash commands in discord.py 2.0

frozen patio
#

It would be interaction.send

hushed galleon
#

why dont i just link the same example from the disnake repo

frozen patio
#

I think

hushed galleon
spring flax
#

What's RecursionError: maximum recursion depth exceeded in comparison?

#

no idea why I am getting that error

cosmic agate
#

i didnt see, sorry

#

umm i dont have access to the account

hushed galleon
spring flax
#

wth

spring flax
# hushed galleon it means your function called itself 1000 times
async def set_build(ctx : commands.Context, gun_name : str, msg : disnake.Message):
    async with bot.db.execute("SELECT url FROM builds WHERE gun = ?", (gun_name,)) as cursor:
        result = await cursor.fetchone()
        if not result:
            author = msg.author.id
            image = msg.attachments[0].url
            await bot.db.execute("INSERT INTO builds (gun, url, author_id) VALUES(?, ?, ?)", (gun_name, image, author,))
            await bot.db.commit()
            embed = Embed(f'Set a build for {gun_name}')
            return await ctx.send(embed=embed)
        else:
            e = ErrorEmbed('That build is already set.')
            await ctx.send(embed=e)



@bot.command()
async def setbuild(ctx, gun_name : str, message : disnake.Message):
    await setbuild(ctx, gun_name, message)

#

why?

hushed galleon
#

you called your command instead of your function

#

probably a good idea to give them more distinct names

spring flax
#

whoops lol

hushed galleon
#

or actually combine them into one

spring flax
#

the function and command?

hushed galleon
#

if your other commands need setbuild, you can call the command as if it was a regular function

#

considering the two have the same signature that is

spring flax
#

I changed the command name

hushed galleon
#

uhh you probably dont want to create another bot class

#

you should store that persistent_views_added = False as a bot var in your main file (also consider a more descriptive name), then check that bot var in your cog's init method and add the view there

#

as a bot var, i.e. ```py

main.py

bot = commands.Bot(...)
bot.persistent_views_added = False```

#

that way if you reload the cog, it doesnt forget that the view is already added

#

oh wait, that also means updating your view wont work...

#

hmm maybe a better way would be storing your persistent view then calling View.stop() during cog_unload

lone hare
#

can anyone help

vale wing
#

Just override the start method of the bot and add the views there, it's called only once so you don't have to worry about duplicate views

vale wing
#

Just like you overwrote on_ready

#

Almost

hushed galleon
#

you wouldnt be able to reload it in your cog and you might find it less organized, but that would work

lone hare
vale wing
#

Simple OOP inheritance

#
class MyBot(commands.Bot):
    ...

    async def start(*args, **kwargs):
        # add views here
        ...
        await super().start(*args, **kwargs)```
lone hare
vale wing
#

Not on_ready for god's sake

#

Oh wait no @lone hare

#

Why am I confusing people

vale wing
stray carbon
#
class HelpDropdown(discord.ui.Select):
    def __init__(self, help_command: "MyHelpCommand", options: list[discord.SelectOption]):
        super().__init__(placeholder="Choose a category", min_values=1, max_values=1, options=options)
        self.help_command = help_command
   async def callback(self, interaction):
        embed = await self.help_command.cog_help_embed(self.help_command.context.bot.get_cog(self.values[0]))
        await interaction.response.edit_message(embed=embed)

class HelpView(discord.ui.View):
    def __init__(self, help_command: "MyHelpCommand", options: list[discord.SelectOption], timeout: Optional[float] = 120.0):
        super().__init__(timeout=timeout)
        self.add_item(HelpDropdown(help_command, options))
        self.help_command = help_command

    async def interaction_check(self, interaction) -> bool:
        return self.help_command.context.author == interaction.user

class MyHelpCommand(commands.MinimalHelpCommand):
    def get_command_signature(self, command):
        return f'{self.context.clean_prefix}{command.qualified_name} {command.signature}'

    async def cog_select_options(self) -> list[discord.SelectOption]:
        options: list[discord.SelectOption] = []

        for cog, command_set in self.get_bot_mapping().items():
            filtered = await self.filter_commands(command_set, sort=True)
            if not filtered:
                continue
            options.append(discord.SelectOption(
                label=cog.qualified_name if cog else "Misc",
                description=cog.description[:100] if cog and cog.description else None
            ))
                    
def __init__(self, help_command: "MyHelpCommand", options: list[discord.SelectOption]):

TypeError: 'type' object is not subscriptable
why does it send this error

vale wing
#

Surround list typehint with quotes

stray carbon
#

""?

vale wing
#
options: "list[discord.SelectOption]"```
stray carbon
#

ohk

cold sonnet
hushed galleon
stray carbon
#

oh

frozen patio
#

This command is not working, the console reports a key error

hushed galleon
#

for <3.9 you would have to be type it using typing.List instead

stray carbon
#
onents.py", line 261, in to_dict
    'options': [op.to_dict() for op in self.options],
TypeError: 'NoneType' object is not iterable

^^^ this error is because of older version

pliant gulch
#

You can also just import “annotations” from future

#

Basically auto forward referencing typehints

stray carbon
#

ohk

vale wing
#

What's wrong with just surrounding it with quotes

stray carbon
pliant gulch
vale wing
#

So preference?

vale wing
hushed galleon
vale wing
#

I always typehint tuple[Something], list[Stuff] etc with quotes and haven't faced any issues so far neither I have noticed any style guides going against it

hushed galleon
#

that syntax is only supported in 3.9+

vale wing
#

Pretty sure it works in 3.8 as well

#

But I have no opportunity to test it rn

hushed galleon
#

!pep 535

unkempt canyonBOT
#
**PEP 535 - Rich comparison chaining**
Status

Deferred

Python-Version

3.8

Created

12-Nov-2016

Type

Standards Track

hushed galleon
#

wrong pep...

#

!pep 585

unkempt canyonBOT
#
**PEP 585 - Type Hinting Generics In Standard Collections**
Status

Accepted

Python-Version

3.9

Created

03-Mar-2019

Type

Standards Track

vale wing
#

You don't even need that variable if you are subclassing

#

Eh hold up you can ignore the quotes now?

#

Ok thx for this pep

slate swan
#

@wooden frigate
asycn def start(self):

vale wing
#

He's overriding a method lol

vale wing
#

Remove that variable and add await super().start() with args and kwargs

pliant gulch
#

All it just does it turn typehints into strings during runtime, just automatic forward referencing

#

Then the typehinter does it’s magic

hushed galleon
pliant gulch
#

No

#

It just turns them into strings during runtime

#

Therefor you won’t get an error due to incompatibility

#

Your type checker should understand the string version fine, etc

hushed galleon
#

yeah i meant if the type checker would still understand it

slate swan
slate swan
slate swan
slate swan
#

im tired😔

#

i have a question:
how do u send a message with spaces in them
l
ike
thi
s (without delaying)

torn sail
#

so because you are replacing start the bot won’t call its own start function. Add *args, **kwargs to the parameters for ur start and call the bots original start with await super().start(*args, **kwargs)

vale wing
#

Simple OOP

class MyBot(commands.Bot):
    async def start(self, *args, **kwargs):
        self.add_view(SomeView())
        await super().start(*args, **kwargs)

client = MyBot()```
#

If you name it client

#

But better name it bot

stray carbon
unkempt canyonBOT
#

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

001 | new
002 | line
stray carbon
#

😭

hardy wing
#
button.emoji = "603673342746034176"```
trying to change a button's emoji to a custom emoji how would I format it?
stray carbon
#

<:emoji-name:emoji-id>?

vale wing
#

!d discord.ext.commands.Bot.get_emoji

unkempt canyonBOT
vale wing
#

Errors?

#

Also did the bot launch

stray carbon
vale wing
#

Not sure

#

But I see no serious difference

#

Try it with setup_hook alr then

flat solstice
#

Anyone mind popping over to #help-mango to answer some questions about how I should layout my db tables for my logging events (ik this is sort of #databases related so I'll be asking there as well but since my question is about discord bot logging events I felt asking here would be good as well)

obtuse ridge
#

whats wrong with this its not sending anything?

@client.event
async def on_member_join(member):
    embed=discord.Embed(title=" You have been successfully verified!", description="Thank you for joining - we hope you enjoy your stay.", color=0x00ebff)
    await member.send(embed=embed)
stray carbon
vale wing
#

Is members intent enabled in code and on dev portal?

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

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

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

stray carbon
#

oh

torn sail
#

Should be the same

stray carbon
#

yea

obtuse ridge
vale wing
#

Sry not you

wide rivet
#

How to fix "Improper token passed"? I'm sure token is right.

slate swan
obtuse ridge
#

i still cant get it to work

slate swan
obtuse ridge
slate swan
#

ok show me the code

obtuse ridge
slate swan
#

and youre importing intents where??

#

ok i see

#

yeah idk

wide rivet
stray carbon
#

it needs member.intent = true

slate swan
stray carbon
#

and ur view timeout must be None

#
  • if you are using buttons, they must have custom ids
slate swan
obtuse ridge
#

Another question how do i make link buttons?

wide rivet
slate swan
stray carbon
#
class MyBot(commands.Bot):
  def __init__(self):
    intents = discord.Intents.default()
    intents.message_content = True
    super().__init__(command_prefix=commands.when_mentioned_or("s!", "S!"), intents = intents)

    async def setup_hook(self) -> None:
        self.add_view(MyView())

bot = MyBot()
slate swan
#

then you can see if its actually improper, or youre doing it wrong as ive never used dotenv, i use configparser

stray carbon
#

try this

stray carbon
#

add something in callback?

wide rivet
#

It can't be wrong

slate swan
stray carbon
#

you should use it in main.py file and import view classes using from cogs.cog_name import MyView

slate swan
wide rivet
#

I'll try again.

slate swan
#

youre probably not copying the token

#

i have a feeling hes typing it out

flat solstice
#

I've got a question about how i should structure my events logging over in #help-mango if someone doesn't mind popping over

slate swan
#

how can u possibly fail copying a discord token 🤦🏿

obtuse ridge
#

Does anyone know how to make a link button on discord?

slate swan
#

if its in a cog it would be the first deco

slate swan
stray carbon
#

if main.py @bot.command() else @commands.command()

obtuse ridge
#

it just show on how to do it on discord js

slate swan
unkempt canyonBOT
#

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

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

Note

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

how do i add a link on that though?

slate swan
stray carbon
#

pip install -U git+https://github.com/Rapptz/discord.py update to latest

slate swan
#

the pypi version already has everything

#

iirc pypi and master are the same

stray carbon
#

nvm

#

update it to latest

slate swan
#

Now regular commands have been replaced with slash commands but these are not working with self bots. Is there a way to send a working slash command throught self bot?

flat solstice
unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

no

#

even if its on the dev portal you need to enable it to your bot

stray carbon
placid skiff
#

But what the hell are you trying to do? it's the whole day i see you asking help for this persistent view thing 😆

spice basalt
#

why isn't this giving an output? (the error is "invalid syntax")

placid skiff
#

first of all, message_content intent doesn't exists, it is Intents.messages

slate swan
spice basalt
#

oops

#

😩

placid skiff
#

message_content should tho exist in disnake

#

and it gives you an error when you try to set them?

#

type pip freeze in your terminal and tell me the version of disnake that you have installed

#

are you running your bot on a venv?

#

virtual enviroment

#

Are you using pycharm?

spice basalt
#

if i can't use "None" for the image url, how can i make the image url not appear if member is None?

placid skiff
#

message intents are enabled on developer portal?

slate swan
#
if member is None:
    ...
if member is not None:
    ...
spice basalt
slate swan
#

and it is wrong

#

send the code for your embed.set_image() here

hybrid ravine
#

TypeError: xylo() got an unexpected keyword argument 'pass_context'
can someone help? it keeps saykng i need to pass ctx thru parameters when i call my function but idk how to define ctx

spice basalt
flat solstice
#

I've got a question about how i should structure my events logging over in #🤡help-banana if someone doesn't mind popping over

placid skiff
#

try this:
intents = Intents.all() instead of intents = Intents.default, comment the part where you set some intent to true then add the intents var to the bot constructor

placid skiff
#

then try to access some message content

hybrid ravine
hybrid ravine
#

im running it like asyncio.run(xylo())

#

and if i put ctx it says undefined

slate swan
spice basalt
#

🗿

#

i mean to send the gifs if there isn't a member but if there is a member, it'll be None and this command will just work

slate swan
#

how does that even work?

#

it shouldnt.

spice basalt
#

i'm not sure if it would even work if i put None

hybrid ravine
spice basalt
slate swan
placid skiff
#

wait you are not setting intents D_D

slate swan
spice basalt
#

ok i'll try that 😩

formal basin
#

I don’t understand why this keeps showing up

placid skiff
#

WAIT SO YOU DECLARED A BOT SUBCLASS IN A COG?

hybrid ravine
# slate swan show me the xylo function
@client.command(pass_context=True)
async def xylo(ctx):
    guild = serverid
    await guild.create_text_channel(names)
        for ch in names:
            channelkun = discord.get.utils(guild.channels, name=ch, type="ChannelType.text")
            with open("text.txt", "a")as f:
                f.write(channelkun)
                with open("text.txt", "r")as w:
                    for x in range(channelsz):
                        for line in w:
                            hook = await guild.channel.create_webhook(name=names)
                            if hook.status_code == 200 or hook.status_code == 201:
                                print(f"Created Webhook {hook.url}")```
spice basalt
placid skiff
#

oh my god D_D

slate swan
slate swan
cold sonnet
spice basalt
hybrid ravine
slate swan
cold sonnet
#

show is a couple of lines before that where the error comes

slate swan
slate swan
spice basalt
#

ah

hybrid ravine
formal basin
placid skiff
slate swan
cold sonnet
hybrid ravine
spice basalt
cold sonnet
#

it could be an IDE glitch or way less python knowledge than needed

slate swan
spice basalt
cold sonnet
#

or the links you've put

spice basalt
cold sonnet
#

you can see they're bad urls, they have to end with .gif or .png or something

spice basalt
#

i didn't show the whole thing earlier because i'm afraid of the minaberry one

hybrid ravine
slate swan
spice basalt
#

my bad 😩

hybrid ravine
slate swan
cold sonnet
#

zagzag gone

formal basin
#

There

formal basin
cold sonnet
#

wth

#

why are there 888 break lines

formal basin
cold sonnet
#

get your code on one screen

slate swan
placid skiff
#

you can create the bot class and then create the instance in the same file, it will change nothing. Making them like i did will look better, that's all

hybrid ravine
formal basin
cold sonnet
#

but it clearly is a syntax error

slate swan
cold sonnet
#

you made an if statement and then unindented

slate swan
#

a command that when ran it makes a channel and a webhook in it?

hybrid ravine
slate swan
#

tf is guild = serverid

paper sluice
#

how to access slash cmds in dpy 2.0?

slate swan
#

@hybrid ravine
if ur code works then this works

@client.command()
async def xylo(ctx):
    guild = serverid
    await guild.create_text_channel(names)
        for ch in names:
            channelkun = discord.get.utils(guild.channels, name=ch, type="ChannelType.text")
            with open("text.txt", "a")as f:
                f.write(channelkun)
                with open("text.txt", "r")as w:
                    for x in range(channelsz):
                        for line in w:
                            hook = await guild.channel.create_webhook(name=names)
                            if hook.status_code == 200 or hook.status_code == 201:
                                print(f"Created Webhook {hook.url}")
hybrid ravine
slate swan
#

you dont need to define pass context