#discord-bots

1 messages · Page 819 of 1

honest vessel
#

well ctx.voice_client?

potent spear
placid grove
#

???

#

:(

honest vessel
#

@edgy ospreyshow ur command for join n play first

#

ctx.voice_client i dont think that works

#

u need to save it as a variable or global or shit, and use it

potent spear
# placid grove :(
@bot.command()
async def say(ctx, *, repeatshit="Nothing"):
  await ctx.send(repeatshit)```
placid grove
#

Ok tyy

potent spear
#

I already regret sending that code

edgy osprey
# honest vessel <@!773492810414292993>show ur command for join n play first
        async def join(self,ctx):
          if ctx.author.voice is None:
            await ctx.send("Сперва зайди в голосовой канал")
          voice_channel = ctx.author.voice.channel
          if ctx.voice_client is None:
            await voice_channel.connect()
          else: 
            await ctx.voice_client.move_to(voice_channel)```
I cannot show the "play" command for technical reasons.
honest vessel
#

@edgy ospreyi use cogs and i do this, self.voice = await ctx.author.voice.channel.connect(reconnect=True, timeout=5500)

potent spear
honest vessel
#

ctx.author.voice.channel.connect <- has voice object

#

so i put that to a variableand use self.voice

#

= self.voice.play(FFmpegPCMAudio(url)

#

not every ctx gonna have ur voice-connectiion in it.

edgy osprey
edgy osprey
low marlin
#

well, could be worse

potent spear
edgy osprey
potent spear
potent spear
#

well

#

as you can see, voice_channel = ... will already throw an error

#

you should return if the first IF is true

mortal dove
#

I'm having more problems...

        with open(file, "rb") as f:
            file = discord.File(f, "discordCommand.log")
            embed = discord.Embed(
                title="Log fetched",
                color=c.teal()
            )
            await ctx.send(embed=embed, file=file)

Same error as last time, Cannot send empty message. Although, funnily enough, if I add this

ctx.send(open(file, 'r').read())
```before the 'open' statement, then they both work.
edgy osprey
summer halo
#

Hello , i want the calculator to turn off when the exit button is pressed . how can I write this code ?

potent spear
potent spear
edgy osprey
low marlin
potent spear
honest vessel
honest vessel
#

no codes

#

how can i even try help

unkempt canyonBOT
#

stop()```
Stops listening to interaction events from this view.

This operation cannot be undone.
potent spear
honest vessel
#

that return is wrong indentation

potent spear
red nest
honest vessel
#

@potent spearbe nice or banned

#

for not helping...

potent spear
potent spear
slate swan
#

in

    @commands.Cog.listener()
    async def on_message(self, message):
        message_content = message.content
        if "x" in message.content.lower() or "y" in message_content.lower() and message.author.id not in [botid, redactedid]:
            await message.channel.send(content="z")

and

    @commands.Cog.listener()
    async def on_message(self, message):
        message_content = message.content
        if "x" or "y" in messsage.content.lower() and message author.id not in [ botid, redactedid ]:
            await message.channel.send(content="z")

why is if "x" or "y" in messsage.content.lower() different than if "x" in message.content.lower() or "y" in message_content.lower() (as the latter doesn't work)

#

nvm i got answered

honest vessel
potent spear
potent spear
red nest
final iron
red nest
#

yeah

#

but you can

final iron
#

But you said you need to. You don't

red nest
#

ok ok

honest vessel
#

and prob easier for noobs to understand

red nest
#

yeah

mortal dove
red nest
#

but it's easier for the bot user if there is an await ctx.send() there

honest vessel
#

isnt it like 1 or another

mortal dove
#

Not sure, but removing it didn't fix it.

honest vessel
#

with open(boost_filename_full) as fp:
prep_file = discord.File(fp, filename=boost_filename

#

try declare filename

mortal dove
#

Alrighty

honest vessel
#

file = discord.File(f, filename="discordCommand.log")

mortal dove
#

Nope, same thing

honest vessel
#

thats weird

#

oh

mortal dove
#

Indeed, especially because when I send the contents as text, the file sends

mortal dove
honest vessel
#

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

unique tendon
#

How do I make it do a log or send a message in a diffferent channel when a specific command is used

#

Like if i do !help here, it will send “!help used in #discord-bots” in another channel

honest vessel
#

try:

 await ctx.send(embed=embed, file=File("discordCommand.log"))
mortal dove
#

Oki

unique tendon
#

Can someone help me?

mortal dove
honest vessel
#

@mortal dovein ur code embed=embed, file=File(file))

mortal dove
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not File
    @commands.command()
    async def clog(self, ctx):
        if ctx.author.id not in [724811595976409119, 434405709321338895, 780239337933504552]:
            return
        file = "R:\\VSCode-Projects\\Discord-Bots\\Discord-Bots\\discordCommand.log"
        # await ctx.send(open(file, "r").read())
        with open(file, "rb") as f:
            file = discord.File(f, filename="discordCommand.log")
            embed = discord.Embed(
                title="Log fetched",
                color=c.teal()
            )
            await ctx.send(embed=embed, file=File(file))
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
    @commands.command()
    async def clog(self, ctx):
        if ctx.author.id not in [724811595976409119, 434405709321338895, 780239337933504552]:
            return
        file = "R:\\VSCode-Projects\\Discord-Bots\\Discord-Bots\\discordCommand.log"
        # await ctx.send(open(file, "r").read())
        with open(file, "rb") as f:
            file = discord.File(f, filename="discordCommand.log")
            embed = discord.Embed(
                title="Log fetched",
                color=c.teal()
            )
            await ctx.send(embed=embed, file=File("discordCommand.log"))
#

@honest vessel

potent spear
#

should be file_path for the first one

mortal dove
#

Same error

honest vessel
#

@mortal doveswap last line

#

file=File(file)

edgy osprey
#

Hooray. The code is almost completely working. It remains to understand why the bot cannot send a message after sending the command.

        async def pause(self,ctx):
          await ctx.voice_client.pause()
          await ctx.send("Пауза")
            
        @commands.command()
        async def resume(self,ctx):
          await ctx.voice_client.resume()
          await ctx.send("Возобновление")```
potent spear
mortal dove
# honest vessel file=File(file)

last time it gave me this, File use used for getting file from path

Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not File
potent spear
summer halo
honest vessel
#

ctx is ctx ctx is not == voice

#

i told u before to save object somewhere

edgy osprey
honest vessel
#

ok to explain it better

#

ctx is (user of command)

#

each guy typing command has diffrent ctx

#

@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Возобновление") so how would this work?

#

its not the bots voice u resume?

potent spear
mortal dove
potent spear
honest vessel
#

yeah

#

and this @commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Возобновление") for pause a bot from playing is wrong.

#

that is that guy typing command -> his voice

summer halo
honest vessel
#

aka his ctx

#

context!

honest vessel
#

error tells it

edgy osprey
potent spear
#

voice_client is None and you're trying to pause

#

first thing you need to do is add a check where you can only play and pause shit if the voice_client isn't None

honest vessel
#

@edgy ospreyif same ctx voice question its same still answer

#

if u say pause to command u dont tell bot to pause

#

or resume... await ctx.voice_client.resume()

#

u kinda tell urself

#

you are the ctx

#

u are the author

#

save bot's voice into a global varaible or use cogs what not

#

n say like self.bot_voice = <here u delecare voice object>

mortal dove
#

@honest vessel Ok I got it to work. No clue why it works now and not before but that's life. Code is below if curious ¯_(ツ)_/¯

honest vessel
#

when u connect bot set bot self.bot_voice or self.mybotvoice =

mortal dove
#
    @commands.command()
    async def clog(self, ctx):
        if ctx.author.id not in [724811595976409119, 434405709321338895, 780239337933504552]:
            return
        file_path = "R:\\VSCode-Projects\\Discord-Bots\\Discord-Bots\\discordCommand.log"
        embed = discord.Embed(
            title="Log fetched",
            color=c.teal()
        )
        await ctx.send(embed=embed)
        with open(file_path, "rb") as f:
            file = discord.File(f, filename="discordCommand.log")

            await ctx.send(file=file)
honest vessel
#

that await on ctx.voice-balblabla.connect()

#

then u have bot voice object

#

what u doing now is just try make bot control ur voice

#

will nvr happen

honest vessel
#

i am sure it wont work soon again

mortal dove
#

Me too, but I guess we'll get there when we get there. Thanks for help anyways :)

honest vessel
#

await ctx.voice_client.resume()

#

that is ur voice_client

#

not the bot

#

np

echo wasp
#

hey yall I made this work command and i don't get an error in the console py @commands.command(name='Work') @commands.cooldown(1,21600,commands.BucketType.user) async def Work(self,ctx): await self.open_account(ctx.author) users = await self.get_bank_data() user = ctx.author earnings = random.int(100,5000) em = discord.Embed(title = "McDonald's Worker", description=f"You worked as a McDonald's worker and you got {earnings} for your day of work!!") await channel.send(embed = em)

echo wasp
honest vessel
echo wasp
#

and i get no output

echo wasp
honest vessel
#

user = ctx.author u also use

#

in code but nvr use

echo wasp
#

because i haven't made the bottem part yet

honest vessel
#

all u use is this

echo wasp
#

I was testing the top first

slate swan
#

How do I add text to a white background that expands using pillow?

honest vessel
#
earnings = random.int(100,5000)
        em = discord.Embed(title = "McDonald's Worker", description=f"You worked as a McDonald's worker and you got {earnings} for your day of work!!"
e = random.randint(100,5000)
send(e)
>>> {earnings}
#

all u do is declare a variable n post it

#

copy pasta economi bots 😛

echo wasp
#

Lol i made it myself

#

i just want the embed to send idc care about the top quite yet

edgy osprey
#

Now the bot writes to the chat, but does not perform its main function.
Before editing the code, it was the other way around...

        async def pause(self,ctx):
          if ctx.voice_client is None:
            await ctx.voice_client.pause()
          await ctx.send("Пауза")
            
        @commands.command()
        async def resume(self,ctx):
          if ctx.voice_client is None:
            await ctx.voice_client.resume()
          await ctx.send("Возобновление")```
slate swan
#

both white backgrounds aren't really shaped the same way

edgy osprey
echo wasp
honest vessel
#

thats not bot's voice thats the one who runs command

edgy osprey
echo wasp
honest vessel
#

if ctx.voice_client is None:
await ctx.voice_client.pause()
this gonna try "pause" all who use this command.........

#

maybe ur a troll

edgy osprey
#

I'm just a stupid Russian dude who uses google translator to communicate normally.

honest vessel
#

Nice

#

@edgy ospreyiv told u exactly what u need to know

honest vessel
#

still resume pause aint gonna do shit @boreal ravine

#

its on ctx.voice

honest vessel
#

not on bot voice object

#

@echo wasphe nvr sent it?

echo wasp
echo wasp
boreal ravine
#

why wouldn't it

honest vessel
#

@echo waspi didnt see ur error 😉

echo wasp
#

I commented it out and then noticed my error

honest vessel
#

@boreal ravinecause if i do @commands.command()
async whynot(ctx)::
ctx.voice_state.pause()

edgy osprey
# edgy osprey Now the bot writes to the chat, but does not perform its main function. Before e...
        async def pause(self,ctx):
            await ctx.voice_client.pause()
            if ctx.voice_client is None:
              await ctx.send("Пауза")
            
        @commands.command()
        async def resume(self,ctx):
            await ctx.voice_client.resume()
            if ctx.voice_client is None:
              await ctx.send("Возобновление")```

Guess what? That's right, the code works at 50% again, now the bot performs its main function (stopping and playing music), but does not perform a secondary function (sending a message to the chat)
honest vessel
#

u think i pause the bot?

#

i give up i think its a troll

boreal ravine
#

he's using the bots voice client

honest vessel
#

u sure?

boreal ravine
#

!d discord.ext.commands.Context.voice_client <--

unkempt canyonBOT
#

property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
boreal ravine
honest vessel
#

voiceclient of the one aka author of ctx

boreal ravine
#

no?

honest vessel
#

ok

edgy osprey
#

When because of your stupidity you were recognized as a troll:

outer parcel
#

i just got this weird problem where when i on my bot nothing happens

boreal ravine
#

Errors?

#
  • Did you call the run method?
  • Try running the file using command prompt/shell
slate swan
#

can you tell me how to put the time in the bot's message as shown in this image?

vale wing
#

Scroll up a bit

vale wing
#

Just like to normal text

#

!e from datetime import datetime
print(f'<t:{int(datetime.now().timestamp())}>')

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

<t:1644606031>
vale wing
#

<t:1644606031>

slate swan
#

Thank you!

drowsy condor
#
Code
@bot.event
async def on_member_update(before, after):
    channel = bot.get_channel(935160414965211179)
    if after.bot:
        return 
    if before.display_name != after.display_name:
        emb=discord.Embed(title="Изменение ника", description="**__Информация:__**", color=discord.Color.from_rgb(255, 128, 0))  
        emb.add_field(name="**Пользователь ника:**", value=f"**{before.name}**", inline=False)
        emb.add_field(name="**Ник до Изменений:**", value=f"`{before.display_name}`", inline=False)
        emb.add_field(name="**Ник после Изменений:**", value=f"`{after.display_name}`", inline=False)
        emb.add_field(name="**Сменил:**", value=f"**{before.name}**", inline=False)
        return
    await channel.send(embed=emb)```
#

why does not it work?

quick gust
#

... whats that second return for?

#

and are the indents correct?

drowsy condor
quick gust
#

yeah

drowsy condor
quick gust
#

remove the second return

drowsy condor
#

Ok thnks

#

Is it possible to find out who changed the user's nickname?

#

@quick gust

boreal ravine
#

you can check through auditlogs

echo wasp
#

how to i make my deposit command so when someone runs &dep all it deposits all there money in the wallet to the bank?

#

rn i have &dep 100 they can't do all

slate swan
echo wasp
slate swan
#

Get the the value of the wallet

#

Add it to the bank, cut the max amount from the wallet

#

Ezzz

slate swan
lone lily
#

How i can send file with discord api? without discord.py

velvet tinsel
cold sonnet
#

that's what she said

velvet tinsel
#

?

lone lily
#

because i need do it :)

slate swan
velvet tinsel
slate swan
velvet tinsel
velvet tinsel
slate swan
velvet tinsel
slate swan
#

Dpy is just a wrapper

velvet tinsel
#

api wrapper

#

I need to sleep

slate swan
velvet tinsel
velvet tinsel
#

!ot-names @velvet tinsel

unkempt canyonBOT
velvet tinsel
slate swan
velvet tinsel
slate swan
velvet tinsel
slate swan
unkempt canyonBOT
velvet tinsel
slate swan
#
    @commands.command()
    async def citizenship(self, ctx):
        #all citizenships citizenships
        role1 = ctx.guild.get_role(938834958124978247)
        role2 = ctx.guild.get_role(938834984515555458)

        list_of_roles=[role1, role2]
        citizenship=random.choice(list_of_roles)
        #gce = grant citizenship embed
        gce=discord.Embed(title="Congratulations", description=f"You have been granted {citizenship.mention} citizenship", color=0x4da917)
        citizenshipdenied=discord.Embed(title="Sorry for the inconvenience!", description=f"This has been caused due to you already possessing {citizenship} citizenship.", color=0xff0000)

        for citizenrole in ctx.author.roles:
            if citizenrole in list_of_roles:
                await ctx.send(embed=citizenshipdenied)
                break
                
            else:
                await ctx.author.add_roles(citizenship)
                await ctx.send(embed=gce)```
alpine flicker
#

indeed, it works perfectly with 3 people, can't test with more but from what i've seen so far the so-called "rate limit" isn't that bad, all it does is slow down the process by a few seconds from time to time. but anyway, thanks for your time

slate swan
#

The bot is supposed to cancel when someone has role in list and not give role

#

but the bot gives role and then says that it won't give role anyways

lyric tusk
#

error:
in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: query is a required argument that is missing.

@client.command()
async def anime(self,ctx,*,query):
    try:
        anime = animec.Anime(query)
    except:
        await ctx.send(embed=  discord.Embed(description = "No corresponding anime is found for the search query", color = discord.Color.red()))
        return
    embed = discord.Embed(title = anime.title_english, url = anime.url, description = f"{anime.description[:200]}...", color = discord.Color.random())
    embed.add_field(name = "Episodes", value = str(anime.episodes)) 
    embed.add_field(name = "Rating", value = str(anime.rating)) 
    embed.add_field(name = "Broadcast", value = str(anime.broadcast)) 
    embed.add_field(name = "Status", value = str(anime.status)) 
    embed.add_field(name = "Type", value = str(anime.type)) 
    embed.add_field(name = "NSFW status", value = str(anime.is_nsfw())) 
    embed.set_thumbnail(url = anime.poster)
    await ctx.send(embed = embed)

pls help xD

final iron
#

Also there should be spaces after your commas in the function parameters

#

And don't use a bare exception

#

It's very bad

lyric tusk
#

ok 🙂

cerulean olive
#

so i want 2 use cogs and stuff could anyone give me a template 2 get started with

wild canopy
#

i just copied my bot onto another computer and after installing all the dependecies, everything worked exept the voice, saying PyNaCl is not installed, however it is installed and I could see it on pip list(Its on ubuntu)

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
final iron
#

Get the highest role and then get the permissions

#

!d discord.Role.permissions

unkempt canyonBOT
final iron
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
slate swan
unkempt canyonBOT
#

property top_role: Role```
Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.
final iron
#

I just showed you

slate swan
#

Thats isnt no thing?

#

Good luck finding it

final iron
#

API doesn't lie

#

Can you show the full console output?

velvet tinsel
ruby tinsel
#

Can someone help me?

I try to run this:

class Dropdown(nextcord.ui.Select):
    def __init__(self):
        selectOptions = [
            nextcord.SelectOption(label="test", description="test2"),
            nextcord.SelectOption(label="test3", description="test4"),
                    ]
        super().__init__(placeholder="test5", min_values=1, max_values=1, options=selectOptions)
    
    async def callback(self, interaction: nextcord.Interaction):
        if self.values[0] == "test3":
            return await interaction.response.send_message("testtttt")
        await interaction.response.send_message(f"you chose {self.values[0]}")

class DropdownView(nextcord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(dropdown())

@client.command()
async def test(ctx):
    view = DropdownView
    await ctx.send("test5555", view=view)

And get this as error:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type type is not JSON serializable

I'm not using json in this file / not imported

balmy ivy
#

how do i make it so i can update my commands

#

so like if i make new commands

ruby tinsel
balmy ivy
final iron
balmy ivy
#

i run it and i stop running it but it doesnt go offline until like 20 mins

final iron
#

Alternatively just use cogs

unkempt canyonBOT
#

Hey @ruby tinsel!

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

slate swan
#

hi so i have my discord bot and i set up a task using tasks but when its doing the task commands dont respond is there a way to make bot still be responsive ?

slate swan
#

Tasks code*

#

Yes

#
@tasks.loop(seconds=60)
async def sendmsg():
    with open("tracking.json", "r") as f:
        data = json.load(f)
    with open("UUIDS.txt", "r") as f:
        uuids = f.read().splitlines()
    # for id, players in data.items():
    #     for channel, uuid_list in players.items():
    #         for uuid in uuid_list:
    #             uuids.append(uuid)
    async with aiohttp.ClientSession() as session:
        limiter = AsyncRateLimiter(max_rate=120, interval=20)
        async def fetch(uuid):
            async with limiter:
                async with session.get(f"https://api.hypixel.net/player?key={random.choice(API_KEYS)}&uuid={uuid}") as api:
                    api = await api.json()
                    result = await track(api, uuid)
                    return result
        levels = await asyncio.gather(*(fetch(uuid) for uuid in uuids))
#

track() function is like 500 lines of code so im obv not gonna paste it here

fervent snow
#

So when my bot does a slashcommand it removes the message where the command was used when it replies to it, is there a way of just having reply without deleting the message?

final iron
fervent snow
#

So in other words gotta switch to prefixs?

final iron
#

Yeah

fervent snow
#

Gooot it, thank you!

final iron
#

Something is blocking aka not async

#

This is causing your bot to freeze

slate swan
#

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

slate swan
#

I

final iron
#
           displayname = requests.get("https://api.ashcon.app/mojang/v2/user/"+uuid).json()["username"]
            except Exception:
                displayname = requests.get("https://api.mojang.com/user/profile/"+uuid).json()["name"]
            stats = {"Star ⭐": bw_level, "Overall FKDR": bw_fkdr, "Solo FKDR": solo_fkdr, "Doubles FKDR": doubles_fkdr, "Threes FKDR": threes_fkdr, 
                "Fours FKDR": fours_fkdr, "4v4 FKDR": fives_fkdr, "Final Kills": bw_final_kills, "Solo Final Kills": solo_final_kills, 
            "Doubles Final Kills": doubles_final_kills, "Threes Final Kills": threes_final_kills, "Fours Final Kills": fours_final_kills, 
            "4v4 Final Kills": fives_final_kills, "Overall Final Deaths": bw_final_deaths, "Solo Final Deaths": solo_final_deaths, 
            "Doubles Final Deaths": doubles_final_deaths, "Threes Final Deaths": threes_final_deaths, "Fours Final Deaths": fours_final_deaths,  
            "4v4 Final Deaths": fives_final_deaths, "Overall Wins": bw_wins, "Solo Wins": solo_wins, "Doubles Wins": doubles_wins, 
            "Threes Wins": threes_wins, "Fours Wins": fours_wins, "4v4 Wins": fives_wins, "Overall Losses": bw_losses,
            "Solo Losses": solo_losses, "Doubles Losses": doubles_losses, "Threes Losses": threes_losses, 
            "Fours Losses": fours_losses, "4v4 Losses": fives_losses, "WLR": bw_wlr,  "Beds Broken": bw_beds_broken, 
            "Beds Lost": bw_beds_lost}
            prefix = ""
slate swan
#

didnt change requests

final iron
#

Requests isn't async

#

You need to use aiohttp

slate swan
#

okay my bad

#

didnt see this

final iron
#

Also

#

Check out f strings

slate swan
#

i know f strings

#

ModuleNotFoundError: No module named 'aiohttp'

how do i fix this

slate swan
#

i tried to

slate swan
#

do pip list in cmd

#

didnt work
probs doing it wrong

#

pip list doesnt work?

#

im using py ide

#

do it in console

#

ah ok

#

not python script

#

ok ty

slate swan
manic wing
slate swan
manic wing
#

well you would use =, not call it

slate swan
#

wait really

#

bruh

steel void
#

how do I use random.choice for an f string

#
em = discord.Embed(description = f"{workingList} **${earnings}**", color = discord.Color.blue())```
#

I want workingList to be a randomchoice

slim ibex
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
final iron
#

camelCase should be used for nothing

slim ibex
final iron
slim ibex
#

!pep8 everyone

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

outer parcel
#

i keep on getting this error

#

even thou mememessage is a global variable

#

and when i try to use somewhere else

outer parcel
slate swan
#

U gotta define mememessage

outer parcel
#
@buttons.click
async def next(ctx):
  global memectx
  if ctx.member.id == memectx.author.id:
    name,url,chosen = await searchredditformeme()
    em = discord.Embed(title = name)
    em.set_image(url = url)
    em.set_footer(text=f"{chosen} | Your meme", icon_url=memectx.author.avatar_url)
    global mememessage
    await mememessage.edit(
    embed=em, 
    channel = memectx.channel.id,
    components = [
      ActionRow([
        Button(
          label="Next meme", 
          style=ButtonType().Primary, 
          custom_id="next",
          emoji = {
            "id": "736655059382960313",
            "name": ":catsmack:",
            "animated": True
          },      
        ),
      ])
    ]
  )   
  else:
    await memectx.reply(f"That is not for you {ctx.member.name}")
slate swan
outer parcel
#

Ah ok

#

same error

slate swan
#

Mmmm

outer parcel
#

the main aim of script

#

is that there is a meme

#

and there is button called next meme

#

when you click on it it will refresh and a new meme will appear

#

so i had a global variable to edit that message

final iron
#

Why though

outer parcel
#

because this variable is in a different subroutine

final iron
#

You're essentially making a paginator

pliant mortar
#

!e print('wee')

unkempt canyonBOT
#

@pliant mortar :white_check_mark: Your eval job has completed with return code 0.

wee
outer parcel
#

!e hi = "2" print(hi)

unkempt canyonBOT
#

@outer parcel :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     hi = "2" print(hi)
003 |              ^^^^^
004 | SyntaxError: invalid syntax
cold sonnet
#

ey

pliant mortar
#

!e @client.command()
async def ping(ctx):
await ctx.send(f'pong {round(client.latency*1000)}ms')

unkempt canyonBOT
#

@pliant mortar :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'client' is not defined
cold sonnet
#

yeah that doesn't work like that

slim ibex
#

🗿

cold sonnet
#

and #bot-commands

slim ibex
cold sonnet
#

guys I got the D

slim ibex
#

🧐😳

outer parcel
#

the paginator is not what im trying to do because these new pages are random

#

it will generate random meme

final iron
#

Ok?

#

Make it do that in the next button

outer parcel
#

oh ok

final iron
#

I adapted that same code to my wall paper command, which guess what? Generates new images

slate swan
#

!e ```py
p = 0
print(p)
def l():
global p
p = 1
return p
print(l())

outer parcel
#

but i want to edit the message

slate swan
outer parcel
#

oh wait

final iron
outer parcel
#

i see now

unkempt canyonBOT
#

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

001 | 0
002 | 1
cold sonnet
#

stop it bro

#

this ain't bot-commands

final iron
#

@slate swan #bot-commands

slate swan
#

ok ok ok ok

outer parcel
#

im very confused now

#

im using discord_buttons_plugin

#

so it will be @wintry jay.click

#

we want to check if user clicking it is user

#

then redo the meme command and edit the message

slate swan
#

Why you're using an event

final iron
slate swan
#

While u can do wait_for?

outer parcel
#

because i have to do the same thing twice

#

im still confused why global does not work

slate swan
outer parcel
#

in the same code i used global memectx

#

and it worked perfectly

final iron
#

Why are you using a 3rd party lib for button support

outer parcel
#

it was the only one i can find

slate swan
slate swan
outer parcel
#

ye but i did define it

final iron
#

At least the 2.0 version

outer parcel
#
  message_id = message.id
  channel_id = message.channel.id  
  newchannel = client.get_channel(channel_id)
  newmessage = await newchannel.fetch_message(message_id)
  global mememessage
  mememessage = newmessage
final iron
#

There is a 0% reason to not use discord.py for buttons

outer parcel
#

doesnt work

#

just error with installing new update

#

broken on my side

slate swan
outer parcel
#

i use discord componenets for menu select

final iron
#

Just use disnake smh

cold sonnet
#

can you even say discord-components is a lib

outer parcel
#

it is

final iron
#

It's so bad

cold sonnet
#

it's just so noob

slate swan
#

bro btw they shut their support server down

rustic stratus
#

Could I get help doing stuff, I am kind of a noob at this.

cold sonnet
#

ask without asking to ask

rustic stratus
#

I more mean is this the right place to do that for Discord.py

slate swan
rustic stratus
#

Alright, one second.

slate swan
cold sonnet
#

effort in profile picture

rustic stratus
#

Okay, so here is what I would want help with is I have a bot that looks like this


class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

    async def on_member_join(self, member):
        guild = member.guild
        if guild.system_channel is not None:
            to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
            await guild.system_channel.send(to_send)


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

client = MyClient(intents=intents)
client.run('token')```
and was wondering how I could add commands to start timeouts, ban people, or kick people to the bot?
#

And only let people with certain roles use those commands.

cold sonnet
#

not sure why you're overcomplicating it so much

final iron
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

Alright.

final iron
#

I don't see a need to subclass anything yet

#

Check out this tutorial

#

If you have any questions or concerns, feel free to come back to this channel and ask/tell us

rustic stratus
#

Okay.

#

Thanks.

balmy ivy
cold sonnet
#

indentation sadcatthumbsup

compact ruin
#

Guys is there a way to disable pings for a specific command?

cold sonnet
#

also, just so we're specific, it's an event not a command @balmy ivy

heavy folio
unkempt canyonBOT
#

class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.

This class can be set during [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
compact ruin
#

Eg i do >ping @compact ruin
it does not ping

#

O ty ty

heavy folio
#

do you want it to ping or not

compact ruin
#

nope

balmy ivy
#

so when someone joins my server it sents them a dm

compact ruin
#

ty that will do

cold sonnet
balmy ivy
#

idk

#

why it dont work

cold sonnet
#

indentation?

balmy ivy
#

i am new to this

heavy folio
cold sonnet
#
@bot.event
    async def on_member_join(member):

```now come on
heavy folio
#

it accepts anything with an AllowedMentions instance

cold sonnet
#

deindent everything after @bot.event in that function

heavy folio
#

indentation

cold sonnet
#

!indents

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

heavy folio
#

!indents

compact ruin
heavy folio
#

oop

balmy ivy
cold sonnet
#

what

compact ruin
#

The user does, i was wondering if it was possible to disable pings when actually calling the command

heavy folio
balmy ivy
#

@bot.event()?

cold sonnet
#

no

compact ruin
#

I already have that but example

cold sonnet
#

read the tag

cold sonnet
compact ruin
#

User : >hello @compact ruin

#

That is not the bot its me and the ping will go through

compact ruin
balmy ivy
cerulean olive
#

File "c:\Users\ja\OneDrive\Desktop\DISCORD BOT COGS\bot.py", line 5, in <module>
client = commands.bot(command_prefix = '.')
TypeError: 'module' object is not callable
PS C:\Users\jackr\OneDrive\Desktop\DISCORD BOT COGS>

balmy ivy
#

look at the code again

heavy folio
balmy ivy
#

`@bot.event
async def on_member_join(member):
embed=discord.Embed(title="Welcome", description="👋 Hello welcome to the League 🥳Have Fun Make sure to go follow the rules everything is listed in information ", color=0xe0e0e0)

  await member.send(embed=embed)`
#

what do i change

cold sonnet
#

huh

heavy folio
cold sonnet
balmy ivy
#

yes thats it

compact ruin
#

ima read le api rq

cold sonnet
#

and it's indented really wrong

compact ruin
#

thanks man

balmy ivy
#

but theres no errors

compact ruin
#

Appreciate it

heavy folio
cold sonnet
balmy ivy
cold sonnet
#

both in code and in the dev portal

heavy folio
#

show hos you enabled intents in code

balmy ivy
#

i have dev

cerulean olive
# balmy ivy `@bot.event async def on_member_join(member): embed=discord.Embed(title="W...
@bot.event
async def on_member_join(member):
    try:
        channel = bot.get_channel(PUT UR CHANNLE ID)
        memb = member.mention
        em = discord.Embed(title=':heart: MEMBER JOINED :heart:', description=f"**Welcome to the server {memb}! Please take a look at CHANNLE NAME then go to [#861645234592546816](/guild/267624335836053506/channel/861645234592546816/)**", color=0x5528ec)
        em.set_image(url='UR GIF')
        await channel.send(embed=em)
        print(f"{member} has joined the server.")
    except Exception as e:
        print(f'{e}')
heavy folio
#

!intents

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.

cerulean olive
balmy ivy
#

its not a welcome command it sents them a dm

cold sonnet
compact ruin
heavy folio
cerulean olive
balmy ivy
cold sonnet
#

but you need to pass in your intents

heavy folio
cold sonnet
#

it's not even what he wants wut

balmy ivy
#

bot = commands.Bot(command_prefix="$", intents=...) like this?

balmy ivy
heavy folio
#

no

cold sonnet
#

and to intents you pass something

heavy folio
rustic stratus
#

Okay, so I have the bot.py file, this is the main file, could I somehow split the different things it does like welcome messages, could I put the individual things into different python files, and then having the main .py files run the commands from these files.

#

I can give an example if wanted.

balmy ivy
unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
heavy folio
#

use cogs

balmy ivy
#

idk how

cold sonnet
rustic stratus
#

Yeah, found that, but I more mean could I get help actually doing that.

balmy ivy
#
intents.members = True




bot = commands.Bot(command_prefix="$", intents=...)```
heavy folio
#

what

cold sonnet
#

indentsize wtf

heavy folio
#

dude

balmy ivy
#

thats what i copied

heavy folio
#

theres even an example?

cold sonnet
#

okay, so it's
intents = discord.Intents.default()
and you're fine

balmy ivy
#

nvm i fixed it

cold sonnet
#

well no

balmy ivy
#

i had to import

cold sonnet
#

intents=intents in commands.Bot

cold sonnet
balmy ivy
#

from discord import Intents

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

cold sonnet
#

it's not cogs...

balmy ivy
#

No bro he asked me to use them

#

and i said i didnt know

cold sonnet
#

yes, now you pass intents to your Bot

balmy ivy
#

where

cold sonnet
#

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

#

do not put the dots in your code

#

they're placeholders

balmy ivy
#

this?

cold sonnet
#

and the command_prefix kwarg stays too

#

that's why I put the dots

balmy ivy
#

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

commands.Bot( intents=intents)

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

#

this is what i have

cold sonnet
#
intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="$", intents=intents)
balmy ivy
#

is it right?

cold sonnet
#

what I sent is

heavy folio
balmy ivy
#

ok so if i run the bot the dm thing will work?

heavy folio
heavy folio
balmy ivy
cold sonnet
#

and, for everyone's well-being, please check out Python basics again incase you wanna do more experienced stuff

cold sonnet
rocky trench
balmy ivy
cold sonnet
#

the bot should have access to the member

balmy ivy
#

it didnt sent my alt

cold sonnet
#

saved and restarted your bot

rocky trench
#

Member intents enabled?

cold sonnet
#

left and joined the server

rocky trench
#

Bro?

cold sonnet
rocky trench
#

well as far as I see

rustic stratus
balmy ivy
rocky trench
#

I wouldn't define intents that way. Just do intents = discord.Intents.all()

balmy ivy
#

it works

rocky trench
#

And make sure intents are enabled in the developer portal too

cold sonnet
balmy ivy
#

no i knew it wasnt because i had to restart vscode

cold sonnet
#

all()

rocky trench
#

...

cold sonnet
rustic stratus
rocky trench
#

What is your problem?

#

trying to add a cog?

rustic stratus
#

Yeah, but I can't quite figure out exactly how to use it.

rocky trench
#

I can explain

#

What are you stuck with?

rustic stratus
#

Okay.

#
        guild = member.guild
        if guild.system_channel is not None:
            to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
            await guild.system_channel.send(to_send)``` I want this in a different python file to clean up the main bot.py file, and then I want the bot to run this when the condition is met from the other file.
heavy folio
#

ok so in a cog (you subclass commands.Cog)

rocky trench
#

Just load it

#

class name(commands.Cog)

heavy folio
#

btw good prac to name classes with first letter upper case

rustic stratus
#

Okay.

rocky trench
#

def setup(bot/client, depends on what you use)
bot.add_cog(name(bot))
client.add_cog(name(client))

#

And in ur main file

rocky trench
#

(Also, I advise putting the cog in a folder in the folder of ur main file

rustic stratus
#

Yeah.

rocky trench
#

and bot.load_extension(foldername.filename)

rocky trench
heavy folio
#

you can have a dir ```

#

then load an extension, not a cog, with

#

this ⬇️ in the main file

unkempt canyonBOT
#

load_extension(name, *, package=None)```
Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
final iron
heavy folio
#

👍

cold sonnet
#

disnake event for timeouts?

rustic stratus
#

So this in a different py file.

heavy folio
#

you gotta indent

rocky trench
rustic stratus
#

This isn't the main file.

rocky trench
#

Cog event == commands.Cog.listener()

rustic stratus
#

Okay.

rocky trench
#

And I feel like I'm already spoonfeeding to much

heavy folio
#

that aint spoonfeeding

rustic stratus
#

Sorry.

rocky trench
#

I could just give a tag

#

In discord.py server they would've been mad already

heavy folio
#
class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def on_member_join(self, member):
        pass
# this would ^
# VS

async def on_member_join(self, member):
    pass
# ^ this would'nt fire
rustic stratus
#

So this?

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

    async def on_member_join(self, member):
        pass```
#

Sorry if I am asking to many questions., but I figure double checking doesn't hurt, right?

rocky trench
#

Forgot to define event

rustic stratus
#

Oops.

rocky trench
#

@commands.Cog.listener()
async def ...

#

And in ur import: import discord and from discord.ext import commands

heavy folio
#

oh yeah the listener deco

rocky trench
#

I can't see indents since I'm on phone

slim ibex
#

better way to do listener

@Cog.listener(‘on_ready’)
async def custom_name
rocky trench
#

yh, since u can only have 1 of each async def for example on_message

#

In cog listeners

rustic stratus
#
from discord.py import commands

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

    @commands.Cog.listener()
    async def on_member_join(self, member):
        pass```
This it now?
rocky trench
#

so u use @commands.Cog.listener("typeofevent")
async def whatevername...

slim ibex
#

GreetingMessage

#

PascalCase

rocky trench
#

U still need to add the cog tho

rustic stratus
#

Yeah, now I just add it to the main bot.py file.

rocky trench
#

No

#

Don't forget ur setup function

rustic stratus
#

K.

rocky trench
#

U use bot, so

    bot.add_cog(name(bot))```
#

Don't mind indents, phone pain

slim ibex
#

Just do 4 spaces 🗿

rocky trench
#

Smart

rustic stratus
#
from discord.py import commands

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

    @commands.Cog.listener()
    async def on_member_join(self, member):
        pass
        
        
def setup(bot):
bot.add_cog(greetingMessage(bot))```
This?
rocky trench
#

forgot :

#

def setup(bot):

#

Also

#

replace name with greetingMessage

#
def setup(bot):
bot.add_cog(greetingMessage(bot))```
rustic stratus
#

Okay.

#

Updated the message above, look right now?

rocky trench
#

Should be good

#

What's the filename, and is it in a folder?

rustic stratus
#

From the main folder it's in 'cogs/greetingMessage.py'

rocky trench
#

Alright

#

make a list in ur main file in on_ready event

#
for extension in list_name:                    
    bot.load_extension(extension)
print(f'Loaded{extension})```
#

I can't indent

#

Just make sure u got right indent, it's too hard on phone

rustic stratus
#

So make a list with extensions, and point them to other .python files.

rocky trench
#

list_name = ["cogs.filename", "cogs.filename",...]

slim ibex
#

!d os.listdir

unkempt canyonBOT
#

os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.

This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
rustic stratus
rocky trench
#

Yeah

#

Put it close to on_ready or somewhere easy to find

#

Whats the name of ur cog file?

rustic stratus
#

Just round the top of the code.

rocky trench
#

list_name = ["cogs.greetingMessage"]

slim ibex
#

that’s a bad way

rocky trench
#

That's the way I use 🤷‍♂️

slim ibex
#

as you will have to add to the list each time you make a new cog

#

it’s inefficient

rustic stratus
#

Alright, then I can use the commas to add more cogs.

rocky trench
#

True

slim ibex
#

you can use a for loop using listdir

rustic stratus
slim ibex
#

and load each file

rocky trench
#

U can use it for now 🤷‍♂️

rustic stratus
#

I can change it if I need to.

rocky trench
#

Just try it out

#

Send here for errors, imma go to sleep when u got it working

#

Can I get an update @rustic stratus ?

rustic stratus
#

Yeah, the bot file won't stay open.

rocky trench
#

Error?

rustic stratus
#

No error or anything, just opens than closes.

rocky trench
#

Hmmm

#

Are you running the cog?

#

If yes, don't do that. U only need to run the main file

rustic stratus
#

It's the main file.

rocky trench
#

Ok

rustic stratus
#

I can send the code if you want.

rocky trench
#

Sure

rustic stratus
#

cogs = ["cogs.greetingMessage"]

for extension in cogs:        bot.load_extension(extension)
    print(f'Loaded {extension})

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')
            
    @commands.command(name="ping")
    async def ping(self, ctx: commands.Context):
        """Get the bot's current websocket and API latency."""
        start_time = time.time()
        message = await ctx.send("Testing Ping...")
        end_time = time.time()

        await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")


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

client = MyClient(intents=intents)
client.run('token')```
This is the script without the token of course.
rocky trench
#

Can u send pic?

#

The indents are off for me

rustic stratus
#

Removed the token of course.

rocky trench
#

I see that you use client

rustic stratus
#

But when I try to run it I do actually have the token.

#

Yeah.

rocky trench
#

Where do you set your prefix

rustic stratus
#

Looks like I forgot that.

rocky trench
#

hmmm

rustic stratus
#

But would that make it crash.

rocky trench
#

Is it ok if @slim ibex helps you?

rustic stratus
#

Sure.

rocky trench
#

Its 2 am and I really need some sleep

rustic stratus
#

Yeah, that's okay.

rocky trench
#

(If he wants)

#

Anyways, since u use client: replace all 'bot' with client

rustic stratus
#

Okay.

rocky trench
#

client.load_extension

#

And in the cog too

#

self.client = client
and def setup(client):
client.add_cog(greetingMessage(client))

rustic stratus
#

Donme.

#

Still crashing though, I can see if someone else could help.

slim ibex
#

what happen

rocky trench
#

He has a problem but I need some sleep rn

rustic stratus
#

Bot keeps crashing when launching it.

rocky trench
#

Also, do the for extension in cogs in on_ready

#

Or loop until complete

slate swan
#

also Client doesn't support cogs, you have to use the commands extension

rustic stratus
#

Ahh.

slate swan
#

commands.Bot might be what you're looking for.

rocky trench
#

He used discord.Client

slim ibex
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

Nvm

slim ibex
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
rocky trench
#

Yeah that's what I was looking for

slate swan
#

@rustic stratus are you facing any other issues?

rocky trench
#

@slim ibex he also used bot.load_extension etc when he uses client

#

Might wanna take a look at that, imma leave now. Have a good day/night everyone

rustic stratus
#

Good night.

#

See anything else?

slate swan
#

well, try it out

rustic stratus
#

Crashed.

reef tree
#

Is visual studio code better then repl.it?

rocky trench
#

Yes

slate swan
#

inherit from commands.Bot..?

slim ibex
#

commands.bot?

#

And no need to type hint context

slate swan
slim ibex
#

^

final iron
rustic stratus
#

And that is what I like to call a screwup.

reef tree
#

I used to use it

oblique laurel
final iron
#

Type hinting is good

slim ibex
reef tree
#

Im gonna look at videoz to learn how to code

slim ibex
#

oh well nvm

final iron
#

Well maybe

slim ibex
#

that’s what I heard

final iron
#

It will work without type hinting but linter wont be able to access the attributes of the Context class

rustic stratus
#

Changed commands.bot to commands.command

final iron
#

So no intellisense for you

slim ibex
#

ahh yeah

#

true

slate swan
# oblique laurel Why’s that?

the machines are just severely underpowered, to the point where you would be waiting up to half a minute to get it ready to go. besides your computer is just a way better development environment than one of those instances.

slim ibex
#

shit time to add the type hint everywhere now

oblique laurel
rustic stratus
#

Server's could work.

slate swan
#

repl.it survives only because of new programmers that have no experience with what they're doing, once someone gains some knowledge, they know immediately to abandon repl.it

rustic stratus
#

I think it's really just if it runs python it can run this for the most part.

#

Correct me if I'm wrong.

balmy ivy
#

how could i do this

slate swan
#

do not treat it as such either, just go for a cloud computing service or host it on a machine somewhere

rustic stratus
#

cogs = ["cogs.greetingMessage"]
    

class MyClient(discord.Client):
    async def on_ready(self):
        for extension in cogs:        client.load_extension(extension)
        print(f'Loaded {extension})
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')
            
    @commands.command(name="ping")
    async def ping(self, ctx: commands.Context):
        """Get the bot's current websocket and API latency."""
        start_time = time.time()
        message = await ctx.send("Testing Ping...")
        end_time = time.time()

        await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")


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

client = MyClient(intents=intents)
client.run('token')``` see issues.
oblique laurel
slim ibex
#

Deploy on a VPS

final iron
#

You need to use the bot framework

slate swan
#

computers cost money yk, abusing repl.it's puny instances does you little good. if you want to get started with cloud computing, Amazon and Google have some free options available (although the free options are weak, they are much better than using repl.it to host an app)

final iron
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

I don't really know, this is like, my second bot with discord.py

oblique laurel
rustic stratus
#

Google Cloud.

slate swan
#

you're just being ignorant at this point, if you don't know then you should ask more questions instead of ignoring others efforts.

rustic stratus
#

I think.

oblique laurel
#

Alr, ill look into it

#

Thx guys!

slate swan
#

im coding my discord bot on replit but its hard to add stuff without getting a eroor

left crater
#

replit is mega gay

slate swan
#

and i dont know how to change stuff from message.channel.send to ctx.sed

slim ibex
supple thorn
#

Use a vps

left crater
#

use either visual studio or pycharm

slate swan
#

i have vscode

left crater
#

or sublime

rustic stratus
slate swan
#

but i cant use terminal

slim ibex
slate swan
#

if you're getting errors related to your code, that's not replit.

slim ibex
#

ctx*

slate swan
#

im saying how do i change from messgae.channel.send to ctx.send

supple thorn
#

I know a free one thats 24/7 thats free without having to watch ads

slim ibex
#

pass ctx to function instead of message

slate swan
rustic stratus
#

Okay, thanks.

slim ibex
#

async def command(message) to async def command(ctx)

slate swan
left crater
slate swan
rustic stratus
#
from discord.ext import commands

cogs = ["cogs.greetingMessage"]
    

class MyClient(commands.Bot):
    async def on_ready(self):
        for extension in cogs:        client.load_extension(extension)
        print(f'Loaded {extension})
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')
            
    @commands.command(name="ping")
    async def ping(self, ctx: commands.Context):
        """Get the bot's current websocket and API latency."""
        start_time = time.time()
        message = await ctx.send("Testing Ping...")
        end_time = time.time()

        await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")


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

client = MyClient(intents=intents)
client.run('token')```
This?
slate swan
#

try it and see 👀

slim ibex
#

commands.Bot has a constructor

rustic stratus
#

Crashed.

slate swan
#
import os
import discord

class MyClient(discord.Client):
    async def on_ready(self):
      print('Logged on as {0}!'.format(self.user))
slim ibex
#

it’s probably not working because there is no constructor?

slate swan
#

also @commands.command() decorator won't work for a bot, it's meant for creating commands without binding it to anything. you should use @client.command()

rustic stratus
#

Okay.

rustic stratus
#

Actually, let me see if I can figure out.

slim ibex
#

@bot.command I believe

left crater
#

or client.command

#

also whats the difference

slate swan
#

difference between what?

slim ibex
#

It’s just based on what you name the variable

rustic stratus
#

Ahh, okay.

left crater
#

bot and client

slim ibex
#

if you are not subclsssing

#

but in terms of the lib, bot and client are different

rustic stratus
#

Still crashed.

slim ibex
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
slim ibex
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

I totally didn't forget to re add the token.

slim ibex
#

unless yes you didn’t put the token correctly lmao

rustic stratus
#

Nope, token is in, still crashed.

slim ibex
#

you should learn some Python OOP before doing a discord bot

rustic stratus
#

bot = commands.Bot(command_prefix='?', description=description, intents=intents) Is this the constructor.

slate swan
# left crater bot and client

discord.Client just represents a discord client, with it you are able to receive events, send http requests to discord, etc. meanwhile, commands.Bot is a special subclass of discord.Client meant to provide the functionality that discord.Client does while supporting the commands framework. the commands framework makes creating bot commands super super easy peasy.

rustic stratus
#

Okay, yeah, found this in an example.

slim ibex
#

but if you are subclassing it would be the __init__

#

Dunder method

slate swan
#

what's wrong?

rustic stratus
#

Okay, but I could use my method and it should work?

slate swan
rustic stratus
#

Gonna add the logging and see if that shows why it still won't stop crashing.

left crater
#

How would you get input from multiple people?

slate swan
slate swan
left crater
#

like a rock paper scissors command

#
        return msg.author == ctx.author and msg.channel == ctx.channel
    msg = await bot.wait_for("message", check=check, timeout=30)
    def checktwo(msg):
        return member != ctx.author and msg.channel == ctx.channel
    msg = bot.wait_for("message", check=checktwo, timeout=30)``` would this work
left crater
#

ok

slate swan
#

don't forget to handle the timeout error

left crater
#

ok

rustic stratus
#
from discord.ext import commands
import logging

logging.basicConfig(level=logging.CRITICAL)

cogs = ["cogs.greetingMessage"]

bot = commands.Bot(command_prefix='?', description=description, intents=intents)
    

class MyClient(commands.Bot):
    async def on_ready(self):
        for extension in cogs:        client.load_extension(extension)
        print(f'Loaded {extension})
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')
            
    @Bot.command(name="ping")
    async def ping(self, ctx: commands.Context):
        """Get the bot's current websocket and API latency."""
        start_time = time.time()
        message = await ctx.send("Testing Ping...")
        end_time = time.time()

        await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")


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

client = MyClient(intents=intents)
client.run('token')```

See anything that would make it crash, even with the logging module, it doesn't make a log file.
balmy ivy
#

does anyone know how to make this so like i do this command $pickup and it sents like one of these

slim ibex
#

wtf

#

Why do you have a bot, a bot class and something instantiating the class

slate swan
slim ibex
#

^

slim ibex
#

If it crashes and doesn’t show anything in the console, logging prolly won’t help

slate swan
#

the client is the bot

slim ibex
#

this code is confusing me

slate swan
#

they subclassed it because discord.Client will accept the on_ready method as an event handler

rustic stratus
slate swan
#

logging module doesn't make a file like that sigh

#

stop worrying about logging, nobody advised that anyways

rustic stratus
#

Oh, wait, docs say that.

#

Yeah, I figured that I could maybe get an error message though.

#

I need to go eat.

slate swan
rustic stratus
#

Yeah, gotta eat, gonna be back in probably 30ish minutes if I could still get help then?

slate swan
slim ibex
#

you really only need this

class Bot(commands.Bot):
    def __init__(self):
        ….

    ….

bot = Bot()
slate swan
#

too many people using discord.py without learning basics of python

slim ibex
#

ik

slate swan
#

unfortunate

left crater
#
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\test\main.py", line 393, in checkt
    await ctx.send(msg.content)
AttributeError: 'coroutine' object has no attribute 'content'

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

Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\nikit\PycharmProjects\test\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'content'
C:\Python310\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'wait_for' was never awaited
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

@slate swan

#

thats what happens when run

slate swan
#

wait_for() is a coroutine, it needs to be awaited

left crater
#

it is await though...

slate swan
#

await wait_for(...) (it should be awaited)

left crater
#

msg = await bot.wait_for("message", check=check, timeout=30)

slate swan
#

check more lines, python isn't lying to you.

left crater
#

oh shit im blind lmao

slate swan
#

we've all been there lol

left crater
#

it works thanks

rustic stratus
# slim ibex you really only need this ```py class Bot(commands.Bot): def __init__(self):...
from discord.ext import commands
import logging

logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

cogs = ["cogs.greetingMessage"]

bot = commands.Bot(command_prefix='?', description=description, intents=intents)
    

class Bot(commands.Bot):
    def __init__(self):
        for extension in cogs:        client.load_extension(extension)
        print(f'Loaded {extension})
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')
            
    @Bot.command(name="ping")
    async def ping(self, ctx: commands.Context):
        """Get the bot's current websocket and API latency."""
        start_time = time.time()
        message = await ctx.send("Testing Ping...")
        end_time = time.time()

        await message.edit(content=f"Pong! {round(self.bot.latency * 1000)}ms\nAPI: {round((end_time - start_time) * 1000)}ms")


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

bot = Bot()
client = MyClient(intents=intents)
client.run('token')```
Is this correct?
slate swan
#

pls learn python

rustic stratus
#

Me?

slate swan
#

yes of course

slim ibex
#

oh no

#

not the cog loading in the constructor

rustic stratus
#

Move it out of the constructor?

hoary cargo
slim ibex
#

yeah you should learn OOP before jumping into dpy

hoary cargo
slim ibex
#

The constructor is what is called when the object is instantiated

#

Everything else not part of the constructor should be a seperate method in the class

rustic stratus
#

Okay.

slim ibex
#

methods like that could be like a method to establish database connection, load cogs, etc

slate swan
#

trust me when i say this, put your discord bot project on halt. you are likely very frustrated or confused with your code not working the way you want it to, when in reality your knowledge of python is not developed enough to do what you want to do

slim ibex
#

^

#

it will do you good

rustic stratus
#

Okay.

slim ibex
#

Learn OOP, how to organize the project, creating packages/modules, os module (might be used for things relating to discord bot)

slate swan
#

in short: you don't know enough python, so don't pull your hair out, instead dedicate time towards learning fundamentals. heck, have some fun! make an interactive terminal chat bot, fiddle with classes and read a lot of documentation

rustic stratus
#

Alright.

slate swan
#

some of the best ways to learn include:
reading open source repos on github, reading documentation, reading examples, googling any and all questions you have, and getting practice with actually typing and getting a feel of the language

slim ibex
#

Take notes too

#

Notes have helped me a lot

rustic stratus
#

K

slate swan
#

because it is a language, and should feel like a verbal one at that. you should try to improve on your ability to brainstorm ideas, and turn those ideas into functional code with fluency

slim ibex
#

especially with c# 🗿

final iron
#

Just start off with a simple setup for now

slate swan
#

good luck, this is a really deep rabbit hole (although many people approach it and don't fall in)

rustic stratus
#

Alright, thanks.

balmy ivy
#

how do i make it so when i say a command the $hi deletes

slate swan
#

await ctx.message.delete()

left crater
#

using the delete() function