#discord-bots

1 messages · Page 1090 of 1

potent spear
#

and to hide your keys, you can use a .env file
look more into that

odd mango
#

ooo okay

#

@potent spear can you answer a question related to general python?

potent spear
#

in a correct channel, sure

sick birch
#

You can check out some of our open source projects @unkempt canyon @lament depot, they should have a constants.py file where we use os.environ.get()

potent spear
sick birch
#

Along with a .env file used in docker-compose.yml, but that serves the purpose of loading in the env variables into the docker container

odd mango
#

oh wait, i made a .env file, wrote TOKEN=xyz in it

#

then did client.run(os.getenv('TOKEN'))

#

it didnt work

potent spear
#

you have to load the env first

#

keep it simple ig

digital mason
#

I switched to disnake

#

dpy didnt like my code

fallow mauve
#

bot.run(os.getenv("token"))
what is wrong with this? it says token is wrong but the env is spelled token and the value is a valid token

fallow mauve
fallow mauve
#

print what

#

@potent spear

potent spear
#

the token ofc

fallow mauve
#

ok

potent spear
#

I feel like it's None in your case => not loaded properly

fallow mauve
#

um, how do i do that? like as a string? print("TOKEN_HERE?")

potent spear
#

bruh

#

print(os.getenv("token"))

fallow mauve
#

i tried it didnt work

potent spear
#

define "it didn't work"

fallow mauve
#
  File "main.py", line 15
    print(os.getenv("token"))
    ^
SyntaxError: invalid syntax
#

@potent spear

potent spear
#

you messed up with your previous line

fallow mauve
#

my previous line is @bot.remove_command("help")

#

theres nothing wrong there

left idol
#
await interaction.response.defer()
# a bunch of stuff              
await interaction.response.edit_message(content = None, embed=embed , view=None)

is this the format i'd use if after i click on a button it does a long process?

#

to make sure it does everything in it

fallow mauve
dull terrace
fallow mauve
#

every time in the past ive done it which i cannot count how many times it has needed an @

#

but whatever, now its saying discord.ui isnt a valid module

potent spear
#

I still have to see full error traceback ofc

ivory raptor
#

hi

fallow mauve
#
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    from discord.ui import Button, View
ModuleNotFoundError: No module named 'discord.ui'
``` ok @potent spear
fallow mauve
potent spear
ivory raptor
#

i do this for sending the nez discord button

#

but its doesnt work

fallow mauve
ivory raptor
#

and i dont have error

potent spear
ivory raptor
#
import discord
from discord.ui import View, Button
import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="*", description="bot de test", help_command=None, intents=intents)

@bot.event
async def on_ready():
    print("[Steelfri] CashOutBOT Started")

@bot.command()
async def help(ctx, arg=None):
        embed = discord.Embed(title="Liste des commandes", url="http://steelfriapi.tk",
                              description="Voici la liste des commandes :\n", color=0xBF211E)
        embed.set_footer(text="CashOutBOT - AdminTools",
                         icon_url="https://media.discordapp.net/attachments/823517163847417867/983481287237058601/sapphire.png")
        embed.set_thumbnail(url="https://media.discordapp.net/attachments/823517163847417867/983481287237058601/sapphire.png")
        embed.add_field(name="Requête :", value="`*post`, `*del`, `*delete`", inline=False)
        embed.add_field(name="Tag :", value="`*username`, `*setup`", inline=False)
        embed.add_field(name="Autres :", value="`*help`", inline=False)

        button1 = Button(label="Support", url="http://sapphireapi.tk")
        view = View()
        view.add_item(button1)

        await ctx.send(embed=embed, view=view)

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

whole code

fallow mauve
potent spear
fallow mauve
potent spear
#

since if you read the docs, you should've known

fallow mauve
potent spear
potent spear
ivory raptor
#

how issouserious

fallow mauve
#

put that up somehwere near the top of your code

ivory raptor
#

ayt

#

its not ok ?

fallow mauve
#

no

#

do not do that

ivory raptor
#

okk the version probably changed

#

doesnt work

fallow mauve
#

show me whole code

fallow mauve
#

what is the description for?

#

in line 8

ivory raptor
#

its a old code, i remove that

fallow mauve
#

ok

ivory raptor
#

its for discord py like v1

fallow mauve
#

hold on, so did you copy this code from an older set?

ivory raptor
fading marlin
# ivory raptor its not ok ?

yes, that's ok, setting help_command to none and calling remove_command does the exact same thing, however it is recommended to just set help_command to None

ivory raptor
#

i only copy that

fallow mauve
ivory raptor
#

its not the problem

fallow mauve
#

ok

ivory raptor
#

but i can remove ^^

fallow mauve
#

no dont its not a problem just wasnt sure what it was

ivory raptor
#

okk, so how can i get the button

#

i dont have error

#

the command just dont work

fallow mauve
#

um... i dont see anything wrong. try running the code again

ivory raptor
#

i do like 3 times ..

fallow mauve
#

ok

#

well, you might not be getting an error bcs youre using a bot.event

#

change it to bot.listen

ivory raptor
#

return nothing

fallow mauve
ivory raptor
#

yes

fallow mauve
#

theres youre problem

#

add this up at the top:

#
intents.messages = True
intents.message_content = True
#

im pretty sure you need those, otherwise the commands will only work in dms

torn sail
#

intents.message not a thing but message content ur correct!

ivory raptor
fallow mauve
ivory raptor
#

okk

torn sail
#

you dont need intents.messages

fallow mauve
#

oh

torn sail
#

just message content

ivory raptor
#

what intent.message_content do ?

fallow mauve
#

nvm then, just intents.message_content = True

torn sail
fallow mauve
torn sail
#

yes

ivory raptor
#

i already have that

fallow mauve
#

it automatically can in dms tho which is how i figured that out earlier today

fallow mauve
#

just trust me

ivory raptor
#

okk

fallow mauve
#

i had this same problem earlier today and it fixed it

ivory raptor
#

i have an error with the token wtf

fading marlin
#

you probably haven't enabled message content in the developer portal

ivory raptor
#

i do

fallow mauve
#

also the token needs to be passed as a string, yours is outside of quotes im pretty sure

ivory raptor
#

i reset and change the token

#

and the bot just dont start

fading marlin
# ivory raptor

Reinvite your bot if you haven't already and try turning it off, waiting for a bit, and then turning it back on

ivory raptor
#

but the command work

fallow mauve
potent spear
ivory raptor
#

the bot is up but i dont receive the on ready

#

i know why

#

its ur listen

#

i change bot.event to bot.listen

fallow mauve
#

put () after listen

ivory raptor
#

its working

#

thx <33

fallow mauve
#

any time, u can dm me if you need any more help

ivory raptor
#

aytt

potent spear
#

anyways, don't hardcode your help command

slate swan
potent spear
#

exactly, but since I have no idea how to do this with a button I'm silent

slate swan
#

i just always did it myself

frozen patio
#
Traceback (most recent call last):
  File "c:\Users\Student\Desktop\Developer\Zeus Bot\main.py", line 23, in <module>
    bot.load_extension(f"Cogs.{filename[:-3]}")
  File "C:\Users\Student\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 802, in load_extension
    self._load_from_module_spec(spec, name, extras=extras)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 719, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.changePrefix' raised an error: ClientException: Cog named 'ChangePrefixCog' already loaded
#

How am I getting this error when I start my bot

sick birch
#

Code?

frozen patio
# sick birch Code?

I am doing this with discord.py to load my cogs:

if __name__ == '__main__':
    for filename in os.listdir("Cogs"):
        if filename.endswith(".py"):
            bot.load_extension(f"Cogs.{filename[:-3]}")
slate swan
#

you loaded the cog already somewhere

frozen patio
#

I meant nextcord

frozen patio
smoky cedar
#

Unfortunately this library is broken

#

Might have to fork it myself

wicked atlas
#

that's a rip

#

i didn't check the github 💀

digital mason
#

I'm using disnake for slash commands, and my commands are not appearing in any server, unless I specify a specific one with test_guilds

smoky cedar
#

Yeah they deprecated it but it's honestly a simple fix

#

Trying to access api data that isn't returned

digital mason
#

Is it just a matter of time or I am missing something

smoky cedar
#

and making a failure

frozen patio
#

@slate swan I am only loading them in my main file

frozen patio
slate swan
#

can see ur main file

frozen patio
#
import nextcord
import os
import json
from nextcord.ext import commands
from Tools.utils import getGuildPrefix
from Tools.translate import Translate

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

bot = commands.Bot(getGuildPrefix, intents = intents)

# HELP
bot.remove_command("help") # To create a personal help command 

# Translate
bot.translate = Translate()

# Load cogs
if __name__ == '__main__':
    for filename in os.listdir("./Cogs"):
        if filename.endswith(".py"):
            bot.load_extension(f"Cogs.{filename[:-3]}")

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    print(nextcord.__version__)
    await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name =f"?help"))

# ------------------------ RUN ------------------------ # 
with open("config.json", "r") as config:
    data = json.load(config)
    token = data["token"]
bot.run(token) 
slate swan
#

use a try except block then

frozen patio
#

Hm

#

I tried that

#

But it didn't work

#

How can I do it in the load function

loud junco
#

i mean everytime u tell people stuff they just dont do it like me 🤣

lyric apex
lyric apex
frozen patio
#

I know

#

I did that

#

How can I do the except part

potent spear
alpine pewter
#
            for player in response["data"]["banlist"]:
                if player["name"]:
                    output_str_a += str(player["name"]) + ", "

            embed = nextcord.Embed(title="`Nitrado Obelisk`", description="`🔴` `Banned Gamertag List:`\n" + output_str_a, color=3066993)
            await interaction.followup.send(embed=embed, ephemeral=False)

Does anyone know how I would possibly separate or limit this if it exceeds the character limit on Discord?

lyric apex
potent spear
alpine pewter
#

Got it, will check into that.
Thank you 😄

frozen patio
potent spear
#

You can put that in the bot constructor itself

frozen patio
#

Hm

#

I do it in the on_ready all the time and it doesn't affect anything

#

Alot of people so it

#

do*

potent spear
#

This is a visualisation of that implementation

#

Works, right?

frozen patio
#

Many verified bot devs do the same thing

lyric apex
#

If they do that mean you should also do that? Like creative ideas doesn't take place anyoneSad_Cat

frozen patio
#

Well it works

lyric apex
unkempt canyonBOT
#

exception nextcord.ClientException```
Exception that’s raised when an operation in the [`Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") fails.

These are usually for exceptions that happened due to user input.
lyric apex
#

Use this in except partQtpie

loud junco
#
try:
  #ur code
except errorName:
  #error handling part
lyric apex
#

Lib doesn't exists anymoreSad_Cat

frozen patio
#

I am trying to do this error:

#

ExtensionAlreadyLoaded

potent spear
frozen patio
#

Ok I did that

#

But how can I just not load the cogs that are already loaded

frozen patio
#

But when I do that

#

Another file says already loaded

#

I am just trying to load the files that are not already loaded

slate swan
potent spear
slate swan
#

🐵

potent spear
#

Screams unmaintainable shit

slate swan
#

screams unpythonic

#

they should remember about this

#

get the reference 😳

frozen patio
#

Ok

#

Anyways

#

Could I unload then reload the extensions

loud junco
loud junco
slate swan
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

await reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
frozen patio
loud junco
#
  @commands.command()
  async def reload(self, ctx, arg):
    try:
      if ctx.author.id == 757508305256972338:
        await self.bot.reload_extension(f'commando.{arg}')
        await ctx.send(f'**{arg}** is reloaded')

    except commands.ExtensionNotLoaded:
      await ctx.send(f'**{arg}** is not loaded')
    except commands.ExtensionNotFound:
      await ctx.send(f'**{arg}** is not found')
      
  @commands.command()
  async def load(self, ctx, arg):  
    try:
      if ctx.author.id == 757508305256972338:
        await self.bot.load_extension(f'commando.{arg}')
        await ctx.send(f'**{arg}** is loaded')

    except commands.ExtensionNotFound:
      await ctx.send(f'**{arg}** is not found')
    except commands.ExtensionAlreadyLoaded:
      await ctx.send(f'**{arg}** is already loaded')
``` here is my code if u want some example
slate swan
#

hydrorico reading errors😳

frozen patio
slate swan
#

well you need to load it once

loud junco
#
async def main():
  async with bot:
    [await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py")]
    await bot.start(os.getenv('TOKEN'))

asyncio.run(main())
#

modify it a little urself @frozen patio

frozen patio
#

I am just doing this

loud junco
#

why load and reload

#

whats the point =.=

frozen patio
#

Cause some are loaded and some are not

clever pulsar
#

!e print('Bruh')

unkempt canyonBOT
#

@clever pulsar :white_check_mark: Your eval job has completed with return code 0.

Bruh
slate swan
#

reload should only really be used when the state of the cog changes

loud junco
clever pulsar
#

!e a=1+1
print(a)

unkempt canyonBOT
#

@clever pulsar :white_check_mark: Your eval job has completed with return code 0.

2
loud junco
#
async def main():
  async with bot:
    [await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py")]
    await bot.start(os.getenv('TOKEN'))

asyncio.run(main())
``` @frozen patio
slate swan
loud junco
clever pulsar
loud junco
#

dude

clever pulsar
loud junco
#

wtf is wrong with this kid

clever pulsar
loud junco
#

why flood chat?

clever pulsar
#

E

loud junco
clever pulsar
loud junco
#

...

#
async def main():
  async with bot:
    [await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py")]
    await bot.start(os.getenv('TOKEN'))

asyncio.run(main())
frozen patio
#

This is the first time I have ever seen this

frozen patio
#

Bruh

loud junco
#

and change commando to ur own folder name

frozen patio
#

Bruh

#

How would that fix anything

loud junco
#

that will load all the extension

frozen patio
#

But some are loaded

loud junco
#

is all the cogs in one folder

frozen patio
frozen patio
loud junco
#

🤦

frozen patio
loud junco
frozen patio
#

I think

#

But the code I use has worked forever

#

Hmmmm

loud junco
#

show me the error

#

btw this thing works for u?
await bot.start(os.getenv('TOKEN'))
u need to modify this urself since u are not using replit

frozen patio
#

I do it in a json file

#

Anyways thats not important

frozen patio
# loud junco show me the error
Traceback (most recent call last):
  File "C:\Users\Student\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 714, in _load_from_module_spec
    setup(self, **extras)
  File "c:\Users\Student\Desktop\Developer\Zeus Bot\Cogs\changePrefix.py", line 34, in setup
    bot.add_cog(ChangePrefixCog(bot))
  File "C:\Users\Student\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 554, in add_cog
    raise nextcord.ClientException(f"Cog named {cog_name!r} already loaded")
nextcord.errors.ClientException: Cog named 'ChangePrefixCog' already loaded

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

Traceback (most recent call last):
  File "c:\Users\Student\Desktop\Developer\Zeus Bot\main.py", line 27, in <module>
    bot.load_extension(f"Cogs.{fn[:-3]}")
  File "C:\Users\Student\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 802, in load_extension
    self._load_from_module_spec(spec, name, extras=extras)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 719, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.changePrefix' raised an error: ClientException: Cog named 'ChangePrefixCog' already loaded
loud junco
#

show ur code

frozen patio
#

How much of it

#

I have like 17-20 cogs

#

But this is my main:

#
import nextcord
import os
import json
from nextcord.ext import commands
from Tools.utils import getGuildPrefix
from Tools.translate import Translate

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

bot = commands.Bot(getGuildPrefix, intents = intents)

# HELP
bot.remove_command("help") # To create a personal help command 

# Translate
bot.translate = Translate()

for fn in os.listdir("./Cogs"):
    if fn.endswith(".py"):
        bot.load_extension(f"Cogs.{fn[:-3]}")

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    print(nextcord.__version__)
    await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name =f"?help"))

# ------------------------ RUN ------------------------ # 
with open("config.json", "r") as config:
    data = json.load(config)
    token = data["token"]
bot.run(token) 
loud junco
#

...

frozen patio
#

What

loud junco
#
async def main():
  async with bot:
    [await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py")]
    await bot.start(os.getenv('TOKEN'))

asyncio.run(main())
```copy pasta this
#

jesus christ

frozen patio
#

Where

#

I don't use asyncio

loud junco
#
for fn in os.listdir("./Cogs"):
    if fn.endswith(".py"):
        bot.load_extension(f"Cogs.{fn[:-3]}")
```replace this
loud junco
loud junco
#

oo

frozen patio
#

Yea...

#

Will this work in nextcord

loud junco
torn sail
#

It won’t

frozen patio
#

Hm

#

Then how can I fic the cog error

#

fix

frozen patio
#

Then how can I load all of the extensions successfully

torn sail
#

I’m not sure what’s wrong with ur code

frozen patio
stone beacon
frozen patio
#
import nextcord
import json
from nextcord.ext import commands
from Tools.utils import getConfig, updateConfig

# ------------------------ COGS ------------------------ #  

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

# ------------------------------------------------------ #  

    @commands.command(name = 'changeprefix', 
                        aliases= ["prefix"],
                        usage="<newPrefix>",
                        description="Change the bot's prefix.")
    @commands.has_permissions(administrator = True)
    @commands.cooldown(1, 3, commands.BucketType.member)
    @commands.guild_only()
    async def changeprefix(self, ctx, prefix):


        data = getConfig(ctx.guild.id)
        data["prefix"] = prefix

        await ctx.channel.send(self.bot.translate.msg(ctx.guild.id, "changeprefix", "NEW_PREFIX").format(prefix))
        
        updateConfig(ctx.guild.id, data)

# ------------------------ BOT ------------------------ #  

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

@torn sail This is the cog that supposedly is already loaded

stone beacon
#

The other cogs are loading?

frozen patio
#

Cause this one is being bumb

#

dumb*

stone beacon
#

Disable it rq and see if your other cogs load

frozen patio
#

Uhh

#

Another one is already loaded as well

stone beacon
#

Wack

frozen patio
#

Ikr

stone beacon
#

You're probably loading the cogs somewhere else first?

frozen patio
#

In my main yup

#

Just in the main

stone beacon
#

O0

#

I'm actually stumped

#

Unless nextcord had some update that corelates to how cogs are loaded in d.py

#

I haven't updated nextcord in a bit

slate swan
frozen patio
#

They do

#

Why would I do a JS file in a py project

slate swan
#

...

frozen patio
slate swan
#

Packages are a thing

#

I.e, a directory with a __init__.py

flint isle
#

disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ExtensionFailed: Extension 'cogs.youtube' raised an error: ModuleNotFoundError: No module named 'discord'
my code

import disnake
from disnake.ext import commands
from cogs.listvar import scritch
import json
from youtube_transcript_api import YouTubeTranscriptApi

def setup(bot):
    bot.add_cog(youtube(bot))

class youtube(commands.Cog):
    """A couple of simple commands."""
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command(name='search')
    async def search(self, VID, keyword):
        transcript = YouTubeTranscriptApi.get_transcript(VID)
        print(transcript)
        JsonItem = str(YouTubeTranscriptApi.get_transcript(VID))
        keyval = keyword
        check = json.loads(JsonItem)
        if keyval in check:
            print("%s is found in JSON data" %keyval)
frozen patio
#

YES

slate swan
frozen patio
#

I fixed the cogs loading

#

But

#

The utils folder is broke

#

IT LOGGED IN

stone beacon
#

What was wrong with your utils folder that affected your cogs folder?

flint isle
cobalt jacinth
#

how to auto-reconnect the bot if there is wifi outage ?

gritty briar
#

Hi. I wanted to build a simple Discord Bot for fun. I want to add simple games to it (single or 2 players). Does anyone have any game ideas?

vocal snow
gritty briar
#

Hmmm thanks

#

Also, just wanted your opinion... If there was a bot with fun quizzes and good questions which gives you interesting rewards if you answer correctly, would you use such a bot?

vocal snow
#

Personally no, but there might be others interested in that

gritty briar
#

Ok cool

slate swan
#

😭

quick nest
#

need help w my bot

#
import hikari
import lightbulb
import requests
from bs4 import BeautifulSoup
import re

url = "https://gfuel.com/collections/on-sale"

result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")

sale = doc.find_all('div', class_="product_info")
price = doc.find_all('span', class_="money")

print(doc.find('div', class_='banner_caption').text)
for item in sale:
    saleitems = item.b.text

opentoken = open('token.txt', 'r')


def TOKEN():
    for line in opentoken:
        print(line, end="")


print(TOKEN())


def Gfuelbot():
    bot = lightbulb.BotApp(token=f'(TOKEN)',
                           default_enabled_guilds=(GUILD)
                           )

    @bot.listen(hikari.GuildMessageCreateEvent)
    async def print_message(event):
        print(event.content)

    @bot.command
    @lightbulb.command('sale', 'Prints The Available Tubs')
    @lightbulb.implements(lightbulb.SlashCommand)
    async def ping(ctx):
        await ctx.respond(f'{saleitems}')

    bot.run()


Gfuelbot()
#

when i run /sale it only outputs Ghost Gaming Starter Kit why?

gritty briar
slate swan
slate swan
#
@discord.ui.button(style=discord.ButtonStyle.green, label="=", row=3)
    async def equal(self,interaction: Interaction, button: Button):
        try:
            self.expr = await self.calculate(self.expr)
        except:
            return await interaction.response.send_message("Um, looks like you provided a wrong expression....")
        await interaction.message.edit(content=f"```\n{self.expr}\n```")
``` how can i calculate the expression?
#

error:

slate swan
slate swan
loud junco
#

btw u know how to do raise error in a try except?

slate swan
#

raise

slate swan
loud junco
#
try:
  #blahblah
except NameError:
  #blahblah
else:
  raise error
```something like this
slate swan
#

idk why

loud junco
#

!d finally

unkempt canyonBOT
#

8.4. The try statement

The try statement specifies exception handlers and/or cleanup code for a group of statements...

slate swan
#

Ye

#

nah you shouldnt

loud junco
#

lmao there is such a thing 🤣

slate swan
#

it would always raise the error lmao

loud junco
#

nvr heard of it

#

i want except name error every error shows in my console

slate swan
slate swan
loud junco
#

jesus christ

slate swan
loud junco
slate swan
#

!d yield

unkempt canyonBOT
#

7.7. The yield statement


yield_stmt ::=  yield_expression
``` A [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield) statement is semantically equivalent to a [yield expression](https://docs.python.org/3/reference/expressions.html#yieldexpr). The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements

```py
yield <expr>
yield from <expr>
```  are equivalent to the yield expression statements...
slate swan
slate swan
loud junco
#
try:
  #blah
except NameError:
  #blah
```if i do this unboundlocal error will not be raised
slate swan
#

well them i am correct

#

what does nonlocal do never heard of it

slate swan
#

3 new for me

slate swan
slate swan
#

ive used them all lmao

loud junco
#

kinda scoping error that i always get awhile back then

slate swan
#

Yield assert nonlocal

slate swan
#

!e

assert 1==1
unkempt canyonBOT
#

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

[No output]
slate swan
#

Bruh

#

!e

assert 1==2
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AssertionError
slate swan
#

its quite helpful

loud junco
#

if false statement then raise error?

slate swan
slate swan
#

@slate swan

def myfunc1():
  x = "John"
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2()
  return x

print(myfunc1())

an example! of the usage of the keyword

unkempt canyonBOT
#
Did you mean ...

» empty-json
» except
» environments
» enumerate
» exit()
» for-else

loud junco
#

!e

def myfunc1():
  x = "John"
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2()
  return x

print(myfunc1())
unkempt canyonBOT
#

@loud junco :white_check_mark: Your eval job has completed with return code 0.

hello
slate swan
loud junco
#

what is nonlocal x

slate swan
#

So I can’t calculate in a button?

#

Difference between global and nonlocal?

loud junco
slate swan
#

mhmm k

slate swan
#

🙂

#

!e

true_condition = 1 == 1
false_condition = 1 == 2
print(bool(true_condition), bool(false_condition))
assert true_condition
assert false_condition

@slate swan

austere vale
#
  @commands.command()
  @commands.has_permissions(administrator=True)
  async def warn(self, ctx, user:nextcord.Member, reason):
    try:
      await user.send(f'You have received a warning from the Server: \n{reason}')
      await ctx.send("Done.")
    except Exception:
      await ctx.send("Failed to DM the user, oh well.")

when i warn someone, it only sends the first word of the reason. does anyone know how to fix it?
ex: the reason is "test warning," the bot will only send "test"

unkempt canyonBOT
#

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

001 | True False
002 | Traceback (most recent call last):
003 |   File "<string>", line 5, in <module>
004 | AssertionError
slate swan
#

pretty handy imo

#
let foo = "uwu";
{
foo = "okimii uwu";
console.log(foo); //okimii uwu
}
console.log(foo) // uwu

I love js 😔

slate swan
slate swan
austere vale
#

oh like * in the parameters?

slate swan
loud junco
#

const let and var 💀

slate swan
loud junco
#

but are pepo still using var?

slate swan
slate swan
austere vale
slate swan
#
function uwuuwuwu(){
   var uwu = "okimii";
}
console.log(uwu);

then again this is completely valid

#

are you printing the variable or the function i cant tell

#

my bad

#

okimii become my linter 😔

#

so no local and global scopes?

#

yeah

slate swan
slate swan
#

though if you already have the variable declared, it'll limit the value of the variable if it was declared within the function to the function only

slate swan
slate swan
#
let uwu = "okimii";
function yes(){
    uwu = "Sift";
    console.log(uwu); //Sift
}
console.log(uwu); //okimii```
#

so keywords changes scopes or what im so confused🗿

#

lmao everybody getting a stroke at js, I hate ya'll

#

js's syntax makes me wanna learn assembly

#

eh, only the scoping is a bit tricky

#

and finding errors if you get any

slate swan
slate swan
slate swan
#

so no

#

its fine, I wont report you

#

no thank you

#

feeble okimii

#

i dont hurt females in general

#

general

#

pls dont

#

okay ig we are way off sanity, lets wrap ths up

#

smack the ot on me pls

#

bro

#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

even better

#

lmao

#

🙏

loud junco
slate swan
#

jokes on you i dont have a basement

loud junco
#

btw how do i reduce rate limited though, idk how to reduce the api usage per second(idk what is it called)

slate swan
loud junco
slate swan
loud junco
#

like using the thing from import discord?

slate swan
#

with a request

loud junco
#

what request

#

requesting for id those kind?

slate swan
#

e.g sending a message you would need to make an api call/request to send the message to the api

loud junco
#

still no idea any example?

#

cuz im fed up with my bot keep getting rate limited

slate swan
#

just check the ratelimit on the endpoint

loud junco
#

and i understand nothing

slate swan
#

well did you actually read it or did you only read the first sentence?

slate swan
slate swan
loud junco
#

yes

#

i dont know what is http method

slate swan
#

😵‍💫

slate swan
loud junco
#

is it even possible to define error

slate swan
#

writing nref

#

writing*, need*

loud junco
slate swan
#

imagine sleeping

#

just correct it whatever was wrong, am too lazy to read it and edit it

loud junco
slate swan
#

im not even here😔

tight mica
#

same

desert heart
#

How do you break Discord bots?

#

Can you break ours?

slate swan
#

😳

loud junco
slate swan
#

🤔

loud junco
#

i asked u and u nvr answer me ;-;

slate swan
#

👀

loud junco
light violet
#

Wott is colorama and traceback

vale wing
maiden fable
#

@loud junco what's the issue?

vale wing
#

Colorama is for colored output, traceback is for working with traceback (logic)

light violet
#

Ok

vale wing
#

Colorama is external, traceback is builtin

light violet
#

What is init and its use

vale wing
#

Object initialization

light violet
#

Oo

vale wing
#

I suggest reading about OOP in python

cobalt jacinth
#

how to make the bot autoconnect when network outage ?

maiden fable
vale wing
#

Afaik library automatically reconnects

cobalt jacinth
#

okok

loud junco
maiden fable
#

Show the traceback?

tight mica
desert heart
#

Ah okay.

slate swan
#

How to configure slash command options in disnake?

slate swan
#

@slate swan

#

Nickname change eh

placid skiff
slate swan
#

In discord2, I had to do

#
option1: Option(name = ...)
#

Does not work with disnake tho'. Gives an unhashable error. I can use options = List[Option] in @bot.slash_command(here) but I don't really want to use that.

placid skiff
#

Yup there was something to declare options with that but now it is deprecated, options are passed as parameters

#
@bot.slash_commands()
async def my_command(my_parameter: str):
  ...

there you have an option of string type

slate swan
#

What if I have to add description to those options?

placid skiff
#

Those types are supported, others must be converted implicity, like a basic converter

placid skiff
slate swan
#

Ohh

placid skiff
slate swan
#

Thanks mate :)

#

@placid skiff What if I have to change things like required = False and stuff?

placid skiff
#

So as you do in normal commands, required parameters must be declared before the optional parameters, you declare the optional by assing them a default value of None

@bot.slash_commands()
async def my_command(my_str: str, my_num: int = None):
  ...
slate swan
placid skiff
#

just add this "`" to open and close a string

slate swan
#

Sometimes I wonder what if two IDs are of the same value.

placid skiff
#

try with a triple quote string

left idol
#

in pycord after using interaction.response.defer() i get a leftover response to the command from my bot that says 'The application did not respond' but i know everything has finished after i clicked my button because i have an embed sent out. how would i go about removing this reply message?

placid skiff
#
my_string = """this is
              a multiline
              string
            """
spare urchin
#

im using nextcord and working on slash commands
recently i made a cog and added a slash command (hi) to it...
but its not showing up in the slash commands...

#

have no errors in console

placid skiff
#

slash commands takes up to 1 hour to be registered globally

spare urchin
#

so what i did was created a normal command named test under same folder

#

still didnt work...

placid skiff
#

Uh then you have some problems with the cog, or the bot

#

can't know without an inspection

left idol
#

can always use debug_guild?

#

it should update it asap

spare urchin
#

maybe check that ?

placid skiff
#

No DM sorry, ask here more people could help

left idol
#

also is it possible for when using a slash command, have arguments in a drop down menu?

spare urchin
#
for fn in os.listdir('./cogs'):
   if fn.endswith('.py'):
     client.load_extension(f"cogs.{fn[:-3]}")

@client.command
async def load(ctx, extension):
   client.load_extension(f"cogs.{extension}")
   await ctx.send(f"Enabled {extension}")

@client.command
async def unload(ctx, extension):
   client.unload_extension(f"cogs.{extension}")
   await ctx.send(f"Disabled {extension}")

@client.command
async def reload(ctx, extension):
   client.reload_extension(f"cogs.{extension}")
   await ctx.send(f"Reloaded {extension}")
left idol
#

for example /test role

#

where role would let you choose from options

placid skiff
#

that seems fine

spare urchin
#

slash command (hi)

import nextcord
from nextcord.ext import commands
from nextcord import Interaction

class hi(commands.Cog):

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

    @nextcord.slash_command(name = "vhi", description ="replies with hello")
    async def hey(self, interaction: Interaction):
      await interaction.response.send_message("hi", ephemeral=True)

def setup(client):
  client.add_cog(hi(client))
#

@placid skiff any probs in this?

placid skiff
#

seems not

spare urchin
placid skiff
#

where is the normal command?

spare urchin
#
import nextcord
from nextcord.ext import commands

class test(commands.Cog):

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

  @commands.command()
  async def test(self, ctx):
    await ctx.send("Working...")

def setup(client):
  client.add_cog(test(client))
#

normal one..

placid skiff
#

same way, embed values are strings

spare urchin
placid skiff
#

@client.event something like that

spare urchin
#

um..noo...ig

#

um..ya.. i have

placid skiff
#

what event?

spare urchin
#

on_ready

placid skiff
spare urchin
placid skiff
#

does it shows up?

spare urchin
placid skiff
#

can i see your folder tree?

#

make a screenshot or smth

spare urchin
#
@client.event
async def on_ready():
  print("'Volter' is up and running perfectly... ")
placid skiff
#

where is the main?

spare urchin
#

@placid skiff is it ok?

placid skiff
#

Yeah

spare urchin
#

uhm..so whats the error here

placid skiff
#

Dunno, all seems fine

spare urchin
#

mhm...

placid skiff
#

and check if it works with that

spare urchin
#

ok ty

placid skiff
#

you can even download it then you will have only to change disnake to nextcord, do as you lke

spare urchin
#

i will just try once more like saving all my slash commands first in another file which i made in the main file.. then try your bot/repo

slate swan
#

hey there, how do I send interactive buttons along with a message using discord.ui.Button

spare urchin
#

@placid skiff

#

one more question

#

im using replit is that an issue ?

placid skiff
#

it could be

spare urchin
#

ok...

shrewd apex
slate swan
#

How to get info about user via slash commands?

maiden fable
#

Sure

slate swan
#

inter.author doesn't exist

#

Hello World

left idol
#
@bot.slash_command(description = "Change teams for user")
@commands.has_role("Captain")
async def team(ctx, player: discord.User, team: str, tmz: str):
    class View(discord.ui.View):
        @discord.ui.button(label="Deny", row = 1, style=discord.ButtonStyle.red)
        async def button_callback(self, button, interaction):
            guild = bot.get_guild(GUILDID)
            role = guild.get_member(interaction.user.id).get_role(ROLEID)
            if role is None:
                await interaction.response.send_message(f"<@{interaction.user.id}>, you don't have perms to interact", ephemeral=True)
            else:
                # buncha stuff 
        @discord.ui.button(label="Approve", row = 1, style=discord.ButtonStyle.green)
        async def button_callback(self, button, interaction):
            guild = bot.get_guild(GUILDID)
            role = guild.get_member(interaction.user.id).get_role(ROLEID)
            if role is None:
                await interaction.response.send_message(f"<@{interaction.user.id}>, you don't have perms to interact", ephemeral=True)
            else:
                # buncha stuff

    embed = discord.Embed(title = "Transaction Request", description = f'<@{ctx.author.id}> requests <@{player.id}> to {team} with timezone {tmz}.')
    await ctx.send(embed=embed, view=View(timeout=None))

maybe my format for the command is not good since i have class inside of the function, but idk how to refer to function argument inside of class, but regarding multiple buttons, with this command right now only the 2nd button gets displayed

#

removing row also results in same thing

slate swan
paper sluice
#

doesn't type kwarg in a command option not try to convert in a slash command?

left idol
slate swan
slate swan
left idol
#

I did not realize while writing, thank you!

paper sluice
# slate swan it does, what type did you provide?
@lightbulb.option(
    'channel',
    '...',
    TextableGuildChannel,
    default=None,
    required=False
)

and i get 'hikari.interactions.command_interactions.InteractionChannel', i can't send message to that channel then

slate swan
paper sluice
#

ah ok, ill give it a try

slate swan
#

How to add reaction in disnake?
I tried

MSG = await inter.response.send_message(embed = emb)
await MSG.add_reaction(...)
``` and this did not work.
#

because its interaction responses aren't messages

slate swan
#

Should I instead to inter.reply or inter.send?

slate swan
#

oH. I see.

#

By the way mate, what do you call those responses which are only visible to the author? @slate swan

#

ephemeral response

#

How do you create those?

#

!d disnake.InteractionResponse.send_message the ephemeral keyword

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
slate swan
#

set it to True

#

Thanks mate @slate swan

#

pleasure

slate swan
lament mesa
#

How does discord.py keep the cached objects in sync with changes?

slate swan
#

they most probably update the cache with events internally

maiden fable
#

Yes

dusky pine
#

Because you're never using cname in your code

#

Is cname a global variable?

short silo
#

How can i get label of a button from an interaction ?

slate swan
#
{len(set(client.get_all_members()))}
``` this is correct?
#

no

slate swan
slate swan
tepid sundial
#

Can you tell me about the Discord robot with Python? I want to join Bot in voice Join

slate swan
unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
tepid sundial
#

tnx

heady sluice
slate swan
heady sluice
tepid sundial
#

اینجا فارسی زبون داری؟

heady sluice
tepid sundial
#

im in persian

heady sluice
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

tepid sundial
#

and you?

heady sluice
#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

tepid sundial
heady sluice
#

it was always meant to be

slate swan
#

!ot pls

unkempt canyonBOT
heady sluice
#

bruh we're telling people to go ot yet talk about the name of the ot channel

tepid sundial
#

@fiery sphinx

#

hi my old friend

boreal ravine
slate swan
#

lmao

fiery sphinx
heady sluice
#

what

fiery sphinx
#

dont ping me

tepid sundial
unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

slate swan
#

.....

boreal ravine
#

Mm

heady sluice
#

what

tepid sundial
#

ok ? @fiery sphinx

slate swan
#

why am i always the centre of attraction

#

bye

boreal ravine
#

Stop being so self-centered, you aren't, I obviously am smh

slate swan
#

oof... sorry ig

heady sluice
#

that's a damn good name

fiery sphinx
tepid sundial
#

"/

#

what?

fiery sphinx
#

cuz i said dont ping me

tepid sundial
#

"/

fiery sphinx
#

but you pinged me again

boreal ravine
#

@fiery sphinx @tepid sundial Go to DMs/off-topic channels please

tepid sundial
#

Ok

heady sluice
#

there's no mod that's usually here

slate swan
#

not really..

#

how do I hide the help mapping subcommand thing

paper sluice
slate swan
#

?

fiery sphinx
heady sluice
slate swan
#

yeah

heady sluice
#

but he's not online

#

so I meant in that way

slate swan
tepid sundial
heady sluice
#

!d discord.Member.move_to

unkempt canyonBOT
#

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

Moves a member to a new voice channel (they must be connected first).

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").

Changed in version 1.1: Can now pass `None` to kick a member from voice.
tepid sundial
#

TNX

boreal ravine
slate swan
#

mapping

maiden fable
slate swan
# slate swan hide

you want to hide all commands with no category? or the help command specifically?

maiden fable
#

Just check if Category is No Category

slate swan
#

whats your current code?

slate swan
maiden fable
#

Why u doing that...?

boreal ravine
slate swan
#

its from some tutorial i believe? the interstella0 gist

boreal ravine
#

Decent help command.. but I made a better one a couple months later

slate swan
#

d!paste

#

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

boreal ravine
slate swan
#

my help command just asks to type / and see it urself kek

maiden fable
#

U can simply say it's a slash command

dusky pine
#

i switched to slash commands because I don't want to go through the pain of writing a help command

slate swan
#

cant you make a dynamic one easily

maiden fable
#

Some bots use slash commands completely but still have a help command kek

slate swan
#

like getting all the slash command objects thru the rest or cacheing it and making the help command with it

#

took me a while lol

boreal ravine
# slate swan took me a while lol

Make the class's initializer and add this inside it

super().__init__(
    command_attrs={'hidden': True}
)

This will hide the help command. It's like doing ```py
command = bot.get_command('star-me')
command.hidden = True

slate swan
#

isnt it meant for hiding commands from a cog tho

boreal ravine
#

Yeah

crisp drift
#

It will filter the hidden commands too

slate swan
heady sluice
#

random bullshit go

maiden fable
#

Nice, ot talks

shrewd apex
#

anyone know how to check encoding of text in txt files or any lib that does so

maiden fable
#

SHA Hash or what?

shrewd apex
#

i have some text files i use for translation now they are encoded in accordance to their language sometimes so i need a auto encoding detector
https://en.wikipedia.org/wiki/Windows_code_page

Windows code pages are sets of characters or code pages (known as character encodings in other operating systems) used in Microsoft Windows from the 1980s and 1990s. Windows code pages were gradually superseded when Unicode was implemented in Windows, although they are still supported both within Windows and other platforms, and still apply when...

shrewd apex
maiden fable
#

Ain't all of them UTF-8 encoded?

shrewd apex
#

unfortunately not

maiden fable
#

I mean, u can still use open() and use the string directly, no?

shrewd apex
#

no it gives me a charmap cant decode byte

maiden fable
#

Damn that sucks

#

istg I hate unicode chars sometimes

shrewd apex
#

and even if i read the bytes as string i cant imagine what translation i will get

maiden fable
#

._.

shrewd apex
#

oof google api sucks sometimes

shrewd apex
#

it didnt use cp tho it just like gave utf-16 ig some text files can be opened with multiple encodings

#

how did ur exam go aced it?

#

hunter intrested in multithreading api calls?

slate swan
shrewd apex
#

ooh nice

maiden fable
shrewd apex
#

calculus?

shrewd apex
# maiden fable Huh?

hmm i was working on an autotranslator so i kinda get like arnd 20000 approx characters translated per second wanna make it faster but not sure how to

maiden fable
#

Since iirc threads don't share data directly

shrewd apex
#

!d concurrent.futures

unkempt canyonBOT
shrewd apex
#

i take the returned result and add it in a dict

maiden fable
#

The last few lines

#

But beware, asyncio and threading ain't the best friends

shrewd apex
#

google dont take more than 2000 characters at a timelemon_angrysad

shrewd apex
#

but i am doing that rn i create a processpoolexecutor and create threads tho i never really under stood where to use thread pool executor and where process

maiden fable
maiden fable
shrewd apex
#

welp chardet got a few wrong guess i have to add a few try except blocks

white citrus
#

Can someone help with heroku?

shrewd apex
#

ask

shrewd apex
#

i got some weird af encoding idk wth it is

#

wanna see?

maiden fable
#

Sure, ig

shrewd apex
#
ÊéÃû£ºÈ«ÇòÉñµoʱ´ú ×÷ÕߣºÒ»Ï¦³ÉµÀ

ÁÖÏö´©Ô½µ½Ò»¸öÈ«Ãñ³ÉÉñµÄ³¬Ææ»Ã³¬¿Æ»Ãʱ´ú¡£
´ÓÒ»¸öÉñÐÔÉúÎïÆðʼ£¬½¨Á¢ÉñÓò£¬¾­Óª¾ì×åÐÅͽ£¬µãȼÉñ»ð£¬Äý¾ÛÉñ¸ñ£¬Õ÷Õ½ÍâÓò£¬¶áÈ¡Éñ¸ñ¡£
maiden fable
#

Nice

#

BTW @shrewd apex u ever used logging module?

maiden fable
shrewd apex
#

lmao

paper sluice
maiden fable
shrewd apex
#

looks more like secret nuclear codes

shrewd apex
maiden fable
#

Ofc lol

shrewd apex
#

where?

maiden fable
#

I want to write the logging output to a log file and I have added a FileHandler... But now how tf do I prevent it from writing to stdout and stderr (same for errors)

shrewd apex
#

u could just put that in an except block for error handling

#

u are using subprocess for stdout and err?

crisp drift
#

@maiden fable have you set propagate to False?

shrewd apex
#
If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

Spelling it out with an example: If the propagate attribute of the logger named A.B.C evaluates to true, any event logged to A.B.C via a method call such as logging.getLogger('A.B.C').error(...) will [subject to passing that logger’s level and filter settings] be passed in turn to any handlers attached to loggers named A.B, A and the root logger, after first being passed to any handlers attached to A.B.C. If any logger in the chain A.B.C, A.B, A has its propagate attribute set to false, then that is the last logger whose handlers are offered the event to handle, and propagation stops at that point.

The constructor sets this attribute to True
velvet compass
maiden fable
cold needle
#

hey

maiden fable
cold needle
#

how can i ping a role with a discord bot | pls ping me if you can help

crisp drift
#

You can set propagate value to False then pass your own stream handler into the logger

shrewd apex
#

role.mention

velvet compass
maiden fable
#

Actually it's a discord bot along with which I'm hosting a FastAPI instance. Now, the FastAPI logger does this thing. I have also tried to change sys.stdout and sys.stderr but no luck

maiden fable
crisp drift
#

Also alternatively iirc you can redirect stdout with contextlib

crisp drift
slate swan
#

or if you have it's id you can just <@&id>

maiden fable
#

So there's no app.run() or smth 😔

slate swan
#

e.set_thumbnail(url=member.avatar.url)
AttributeError: 'str' object has no attribute url

#

did this change?

#

Im not using 2.0

paper sluice
#

github copilot

#

there are multiple other autocompleting software

#

i dont use any, but there some good ones, kite, tabnine, github copilot (u have to sign up on their website and wait for months to get this, but its probably the most advanced one right now) intellij, etc

dense swallow
#

hello, im trying to make a command which gets a user's badges... this is custom badges, not hypesquad etc... this is my code: ```py
async def get_member_badges(self, member):
user = self.bot.get_user(member.id)
guild = self.bot.get_guild(764049436275114004)

    staff_role = guild.get_role(849669358316683284)
    partner_role = guild.get_role(972071921791410188)
    booster_role = guild.get_role(782258520791449600)
    contrib_role = guild.get_role(950785470286163988)

    if user.id == self.bot.owner.id:
        return ":developer: Developer"

    if staff_role in user:
        return ":staff: Staff Member in the support server"
    
    if partner_role in user:
        return ":partner: PizzaHat's Partner"
    
    if booster_role in user:
        return ":booster: Booster in the support server"

    if contrib_role in user:
        return ":github: Contributor of PizzaHat"

    else:
        return f"{self.bot.no} N/A"



@commands.command()
@commands.cooldown(1, 3, commands.BucketType.user)
async def badges(self, ctx, member: discord.Member=None):
    """
    Shows different badges of a user.
    If no user is given, return your badges
    """

    if member is None:
        member = ctx.author

    badges_list = await self.get_member_badges(member)

    em = discord.Embed(
        title="User Badges",
        color=self.bot.color
    )
    em.set_author(name=member, icon_url=member.avatar.url)
    em.description = badges_list

    await ctx.send(embed=em)
#

this works, but not as expected.. i want it to show every badge the user has in a new line.. but it only shows one..
example: since im the dev of the bot it only shows developer, but im also a staff member having that role.. how do i do that? i think something's wrong with my ifstatements

slate swan
#

kite

#

its not as much as developed as copilot, but kinda helpful

#

RooLook i've used github copilot.... and its kinda annoying

maiden fable
maiden fable
dense swallow
#

so return ["things here"]

maiden fable
#

Inside the if statements, append to a list and return the list at last

dense swallow
#

i got the list part.. but didnt get what u mean by append and return at last

#

like this? ```py
async def get_member_badges(self, member):
user = self.bot.get_user(member.id)
guild = self.bot.get_guild(764049436275114004)

    staff_role = guild.get_role(849669358316683284)
    partner_role = guild.get_role(972071921791410188)
    booster_role = guild.get_role(782258520791449600)
    contrib_role = guild.get_role(950785470286163988)

    if user.id == self.bot.owner.id:
        dev = [":developer: Developer"]

    if staff_role in user:
        staff = [":staff: Staff Member in the support server"]
    
    if partner_role in user:
        partner = [":partner: PizzaHat's Partner"]
    
    if booster_role in user:
        booster = [":booster: Booster in the support server"]

    if contrib_role in user:
        contrib = [":github: Contributor of PizzaHat"]

    else:
        return f"{self.bot.no} N/A"

    return [dev, staff, partner, booster, contrib]
maiden fable
#

Got it? @dense swallow

slate swan
#

you are interested in using the in on user.roles instead of user itself

dense swallow
#

yeah

#

kinda, ill try that

slate swan
#

actually no, you can directly use member.roles, too much of useless code there

dense swallow
#

instead of: if role in user

slate swan
#

yep.

#

but that wont work,since user there needs to be a discord.Member, and you have a User

slate swan
#

Dear, how to display in the chat not the author, but the user of which I will ping in the command !command @echo breach#0000

#
          url = str(ctx.author.avatar_url)[:-10]
#

so that instead of the author there was another

dire folio
#

???

slate swan
#

?

dire folio
#

What do you mean

slate swan
#

I want that when I enter the command, not my avatar is displayed, but another user whose ping

granite parcel
#

how to check if user has nitro?

granite parcel
dire folio
#

If u use ctx.author.avatar_url

dense swallow
unkempt canyonBOT
dire folio
#

It will do whoever did the cmd

granite parcel
dense swallow
slate swan
granite parcel
slate swan
granite parcel
dire folio
#

^

granite parcel
#

we cant assume

scarlet aurora
#

Can someone tell me why bot is not defined? I normally do commands like @commands.command()

unkempt canyonBOT
#

Hey @slate swan!

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

dense swallow
unkempt canyonBOT
scarlet aurora
granite parcel
scarlet aurora
#

yes

dense swallow
slate swan
#
   @commands.has_role(982744620792426537)
    @commands.command(name = "бан", aliases = ["забанить", "ban"])
    async def command_clear(self, ctx, *, member: discord.Member, reason = None):

        try:
            await ctx.channel.purge(limit = 1)
            # await member.ban(reason=reason)

            img = Image.open("./ImageO/ban/фон.png") # открыл картинку с фоном

            url = str(ctx.author.avatar_url)[:-10] # создал переменную URL аватарки моей -10 символов с конца

            url1 = requests.get(url, stream = True) # Сделал юрл более оптимизированным
            url1 = Image.open(io.BytesIO(url1.content))
            url1 = url1.convert('RGBA') # конфертировал аву в РГБА
            url1 = url1.resize((1850, 1850), Image.ANTIALIAS) # Изменил ширину и высоту авы

            url1M = Image.new('L', url1.size, 0 ) # Создал картинку. Где L означает черно белая для маски нужна. url1.size перенимает size. 0 прозрачность
            idrawM = ImageDraw.Draw(url1M) # говорим что переменной idrawM будем рисовать чтонибуить на url1M
            idrawM.ellipse((0, 90, 1850, 1800), fill=255) # Рисуем элипс. координаты 0 с права, 90 с верху, 1850 ширина, 1800 высота. 225 непрозрачная

            img1 = Image.open("./ImageO/ban/Рамка1.png") # открыл рамку
            img1M = Image.open("./ImageO/ban/РамкаМ.png").convert('L') # открыл маску для рамки. конвертировал в чернобелую картинку
            
            img.paste(url1, (2575, 730), url1M) # соеденил img и url1. координаты url1 2575 справа и 730 с верху. наложил на url1 маску (url1M)
            img.paste(img1, (0,0), img1M) # соеденил img и img1 с координатами 0 справап и 0 сверху. наложил на img1 маску (img1M) 
            img.save('./ImageS/user_card.png') # сохранил картинку

          await ctx.send(file=file1, embed=embed)
            os.remove("./ImageS/user_card.png
scarlet aurora
granite parcel
dense swallow
scarlet aurora
#

oh sheet i forgot about all of that, thanks

slate swan
dire folio
#

member.avatar_url

slate swan
#
           url = str(ctx.member.avatar_url)[:-10] # создал переменную URL аватарки моей -10 символов с конца

slate swan
granite parcel
#

1.7.3 i think

granite parcel
granite parcel
#

oh god

dire folio
slate swan
#

i believe you dont need to use requests to get the bytes, discord.py has inbuilt methods for that which im unable to recall for 1.7.3

sick birch
dire folio
#

Nah

slate swan
#
            url = str(member.avatar_url)[:-10] # создал переменную URL аватарки моей -10 символов с конца

🥺

sick birch
#

Probably has to do with the splicing at the end there

granite parcel
#

but why str?

slate swan
#

I do not know. how is it necessary?

scarlet aurora
#

TypeError: on_message() missing 1 required positional argument: 'message' Can someone tell me why this is happening?

paper sluice
#

is that inside the class?

scarlet aurora
#

yes

paper sluice
#

!paste can u send ur code

slate swan
#

Oh. I figured it out. Thank you dear

scarlet aurora
#

alright

granite parcel
#

help god

scarlet aurora
#
    @commands.Cog.listener()
    async def on_message(self, ctx, message):
        if '' or '' or '' or '' in message.content:
            await message.delete()
            message_redo = message.replace('e', '3').replace('a', '4')
            await ctx.send(message_redo)```
slate swan
#

😔 why are people so obsessed with ctx, they dont even spell it right, its context

scarlet aurora
#

ctx is shorten for it

sick birch
#

probably because commands use context

slate swan
#

yeah, still, you wont be using it in on_command events

sick birch
#

I don’t understand that first if statement lmao

scarlet aurora
#

can i send messages on an event?

paper sluice
#

yes

sick birch
#

Sure

#

Depending on the event

paper sluice
#

message.channel.send or make a channel object and send

sick birch
#

Probably can’t in the on connect one

slate swan
#

why not, the message provides you most of the things context does

scarlet aurora
#

await message.send like dis?

sick birch
#

Since ctx is just a shortcut binding to many message attributes anyway

paper sluice
granite parcel
scarlet aurora
shrewd apex
#

u have to add a channel like message.channel.send()

paper sluice
shrewd apex
#

or ctx for short in most cases

scarlet aurora
#

alr

granite parcel
shrewd apex
#

what event

granite parcel
#

on_message