#discord-bots

1 messages ยท Page 255 of 1

slate swan
#

Does it return an int or a string

formal basin
#

r = redis.Redis

#

cant show you rest

slate swan
#

So r.get(f"vchannel...") returns None

#

You won't go far if it returns that

formal basin
thin raft
slate swan
#

Again, int or string

formal basin
#

do i put it in string

formal basin
slate swan
#

Channel IDs are integers

formal basin
formal basin
slate swan
#

Then use something like

channel1 = client.get_channel(...) or await client.fetch_channel(...)
#

It first tries to get it from cache, if it's not found and returns None it will make the API call with fetch

slate swan
#

No you're not

formal basin
#

im using that

slate swan
#

And? Where's the second part?

formal basin
#

channel

slate swan
#

I told you to use

channel1 = client.get_channel(...) or await client.fetch_channel(...)

#

Do you see that anywhere in your line? No.

#

The entire thing is a line

formal basin
#

wait

slate swan
#

You don't choose between get_channel or fetch_channel

#

You write them both with an or operation in the middle

formal basin
#

ohhhhh

#

ok

slate swan
#

!e ```py
print(None or "something")
print("something" or "other something")
print("something" or None)
print(None or None)

unkempt canyonBOT
#

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

001 | something
002 | something
003 | something
004 | None
slate swan
#

if the first thing is not truthy it will get the other thing instead

#

we try to get channel from the cache but if its not here we fetch api

formal basin
#
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "/Users/zagzag/vscode/zagzag.py", line 500, in verify_setup
    channel1 = client.get_channel(channel) or await client.fetch_channel(channel)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 2565, in fetch_channel
    data = await self.http.get_channel(channel_id)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/http.py", line 745, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In channel_id: Value "b'1112053260879147133'" is not snowflake.

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

Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'verify-setup' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In channel_id: Value "b'1112053260879147133'" is not snowflake.```
#

what is a snowflake supposed to be

slate swan
#

it must be int not bytes

#

convert it to int

formal basin
slate swan
formal basin
#

oh ok

oblique trail
#

Is python the best language for discord bots

formal basin
#

its easier than js

formal basin
slate swan
#

no idea how redis stores values

#

You get bytes back so decode them and convert to int when you get the channel ID

#

!e

x = b"123456789"
print(int(x.decode("utf-8")))
unkempt canyonBOT
#

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

123456789
oblique trail
#

I donโ€™t remember the name

slate swan
#

lua

#

They're not unknown if "many" people use them

oblique trail
oblique trail
slate swan
formal basin
slate swan
#

Many people use some unknown language

Then you're contradicting yourself

oblique trail
#

He sued

#

Hikari

#

Itโ€™s unknown for me atleast

#

Like compared to the top ones

slate swan
#

It's not a language

#

It's a library

oblique trail
#

Oh

slate swan
#

Language is still Python

oblique trail
#

I meant that

#

I think I used

slate swan
oblique trail
#

Yea i know

slate swan
#

Heard about Hata

oblique trail
#

Whatโ€™s that

glad cradle
#

!pypi Hata

unkempt canyonBOT
#

A powerful asynchronous library for creating Discord bots in Python.

thin raft
slate swan
oblique trail
#

Oh

formal basin
#
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/zagzag/vscode/zagzag.py", line 619, in on_message
    channelv2 = int(channelv.decode("utf-8"))
AttributeError: 'NoneType' object has no attribute 'decode'
slate swan
#

channelv is None

formal basin
#

ok

#
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/zagzag/vscode/zagzag.py", line 141, in on_member_join
    await channel.send(message.format(mention=member.mention))
AttributeError: 'bytes' object has no attribute 'format'```
slate swan
#

you need to decode it

formal basin
#
@client.event  
async def on_member_join(member):
 try:
  channel1 = r.get(f"channelid {str(member.guild.id)}")
  channel2 = int(channel1.decode("utf-8"))
  channel = client.get_channel(channel2) or await client.fetch_channel(channel2)
  message =  r.get(f"message {str(member.guild.id)}")

  await channel.send(message.format(mention=member.mention))
 except KeyError:
      pass```
#

i have

#

look

slate swan
#

yes still the same answer you need to decode it

formal basin
#

wdym

slate swan
#

redis always returns bytes

formal basin
#

it is decoded

slate swan
#

where is message decoded

formal basin
#

why does message need to be decoded?

#

its not an int

slate swan
#

cause its bytes?

slate swan
#

if its int you need to cast it into int

formal basin
slate swan
#

no it will be string already

formal basin
slate swan
glad cradle
#

btw isn't there and async thing to work with redis?

#

iirc there is

slate swan
#

there is

formal basin
#

so if i decode it to a int then it will still be an string

slate swan
#

but i aint explaining that

glad cradle
#

!pypi aioredis

unkempt canyonBOT
formal basin
glad cradle
slate swan
slate swan
#

!pep 3156

unkempt canyonBOT
#
**PEP 3156 - Asynchronous IO Support Rebooted: the "asyncio" Module**
Status

Final

Python-Version

3.3

Created

12-Dec-2012

Type

Standards Track

glad cradle
#

well not sure if it explains that

slate swan
#

TypeError: object NoneType can't be used in 'await' expression

slate swan
#

and full traceback

#

Traceback (most recent call last):
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\chain\Desktop\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Soul Client #1\Server Backup\bot.py", line 42, in on_ready
await register_cogs_async()
File "C:\Users\chain\Desktop\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Soul Client #1\Server Backup\bot.py", line 37, in register_cogs_async
await client.add_cog(Commands(client))
TypeError: object NoneType can't be used in 'await' expression

Code:
async def register_cogs_async():
"""Register cogs for the bot asynchronously."""
await client.add_cog(Commands(client))

slate swan
#

Code:
async def register_cogs_async():
"""Register cogs for the bot asynchronously."""
await client.add_cog(Commands(client))

#

yes, still the same question

slate swan
#

where do you call register_cogs_async

#

async def register_cogs_async():
"""Register cogs for the bot asynchronously."""
await client.add_cog(Commands(client))

@client.event
async def on_ready():
await register_cogs_async()

slate swan
#

and may i know why you load cogs this way and not using setup function?

#

like this

#

Hey there ๐Ÿ˜ Iโ€™m looking for a solution, last step for the connection with discord

slate swan
#

What python version is that

winter hare
#

is there a way to send a message that mentions a user and a embed at the same time with on_member_join

naive briar
#

Just do it in the event

slate swan
sick birch
# winter hare is there a way to send a message that mentions a user and a embed at the same ti...
await channel.send(member.mention, embed=embed)

Where:

  • channel is a subclass of type discord.abc.Messageable, represeting the channel you want to send the message to
  • member, an instance of discord.Member representing the user you want to mention (assuming this is in an on_member_join event, it'll probably be the newly-joined member)
  • embed, an instance of discord.Embed representing the embed you wish to send in the message
slate swan
buoyant quail
#

I'd say the problem is coding on phone :p

You didn't get errors when installing the library?
Try to reinstall the library. Seems that one of the depencies is not installed correctly.

lethal drift
#

What's the correct way to get the reacted emoji name when using

def check(channelID, user, emoji):
    if channelID == context.channel.id:
        if user == "everyone":
            return True
        elif int(user) == context.author.id:
            return True


bot.wait_for(..., check=check)

#

I don't know how I'd get the reactions

buoyant quail
#

It's reaction_add event

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
buoyant quail
#

there is an example with reaction

tropic flicker
#

line 9, in <module>
@bot.event()
^^^^^^^^^^^
TypeError: Client.event() missing 1 required positional argument: 'coro'
Error^

import discord
from discord.ext import commands

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

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

@bot.event()
async def on_ready():
print('{0.user} is online')

@bot.command()
async def discord(ctx):
await ctx.send('')

bot.run('')
Code^

turbid condor
#

@bot.event

tropic flicker
slate swan
#

No

#

It's just putting for example Discord Android in the identify payload when you connect to the gateway, which isn't what should be done as per documentation, but Discord showing the status for bots is their problem

#

Discord's documentation wants you to put the library's name in the connection properties of the identification payload

#

If you don't put that but something else, it's not a big deal just not want Discord wants - but not against ToS

slate swan
#

Nice rectangle you got here

#

Then just ask your Discord bot related questions here

naive briar
#

You didn't ask any questions

slate swan
#

Not if you just send some random picture with no context

#

Just ask your questions here if you can't send pictures wherever you want to send pictures

naive briar
#

have to huh

slate swan
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

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

Why do you do ctx.author.user.name

#

author is already a user

#

And it's avatar.url not avatar_url

slate swan
clear lark
#

How do you make a cog do something every time its loaded?

tidal folio
#

Why Errol?

slate swan
#

You can't await a function that isn't a coroutine

#

asyncio.sleep you can await

tidal folio
slate swan
#

You need to import asyncio obviously

tidal folio
slate swan
#

Slash commands have nothing to do with that

#

You can import whatever you want whenever you want in any python file, as long as it's installed

tidal folio
slate swan
#

Just. Do. It

slate swan
#

Then you know your question doesn't make sense

#

And if you sleep 10 seconds, you'll need to defer

tidal folio
slate swan
#

You even responded to that message asking if using import works in slash commands

#

Which, as mentioned, doesn't make sense

tidal folio
#

Yes ty

tidal folio
slate swan
#

And again, it's not time.sleep but asyncio.sleep

tidal folio
slate swan
#

About something that was said less than 10 minutes ago

tidal folio
bright lake
#

anyone can help?

output

#

source

from discord.ext import commands
import os
import asyncio
import datetime

client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
col = discord.Color.from_rgb(3, 240, 252)
feedback = 1121065558121656372

@client.event
async def on_ready():
    print("Success: bot is connected to Discord")

class SuggestModal(discord.ui.Modal, title="Send a suggest"):
        
    sg = discord.ui.TextInput(label="Send us your suggest", placeholder="eg. add minigame", required=True, min_length=20, max_length=2000, style=discord.TextStyle.paragraph)
    
    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting your suggest, the moderation team will see it momentarily!", ephemeral=True)
        
        channel = client.get_channel(feedback)
        
        embed = discord.Embed(
            title="Suggest from member",
            color=col,
            timestamp=datetime.datetime.now()
        )
        embed.add_field(name="User name:", value={interaction.user.name}-{interaction.user.discriminator})
        embed.add_field(name="Suggest:", value={self.sg}, inline=False)
        embed.set_thumbnail(url=interaction.user.avatar)
        
        await channel.send(f"<@&1100415432567033916> New feedback, check it!", embed=embed)
                
@client.tree.command(name="suggest",description="Send a suggest to server")
async def suggest(interaction: discord.Interaction):
    await interaction.response.send_modal(SuggestModal())```
slate swan
#
embed.add_field(name="User name:", value={interaction.user.name}-{interaction.user.discriminator})

Unsure why you are subtracting the discriminator from the username

#
embed.add_field(name="Suggest:", value={self.sg}, inline=False)

You are setting the value to be the TextInput object rather than the value of it - self.sg.value

thin raft
#

have you coded that?

slate swan
#

i dont think we can help on that

#

!rule 5

#

Sounds like rule 5 as well bravemmlol

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

slate swan
#

And that looks very AI generated weird code

thin raft
slate swan
#

So you broke 2 rules - 5 and 10

thin raft
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

#

:x: Invalid rule indices: 55

thin raft
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

slate swan
naive briar
unkempt canyonBOT
slate swan
#

!rules

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

slate swan
#

Yeah it's not a channel to get all rules sent

thin raft
#

you need to follow all of them not just 1

slate swan
#

isnt that obvious

thin raft
#

apparently not

slate swan
#

!d nextcord.ext.commands.Bot

unkempt canyonBOT
#
class nextcord.ext.commands.Bot(command_prefix=(), help_command=..., description=None, *, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, ...)```
Represents a discord bot.

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

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

there is something like delete_after

naive briar
#

Its embed? You mean only the embed or the message?

slate swan
#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
slate swan
#

delete_after kwarg

#

delete_after (float) โ€“ If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

naive briar
#

What object do you think that's from

slate swan
#

it will delete whole message it just sent

naive briar
#

!d discord.Message.delete

slate swan
#

yeah

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other peopleโ€™s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
naive briar
#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is โ€œsyntheticโ€ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

naive briar
#

(There's docs for a reason)

slate swan
#

no

#

the delete method wont just appear out of nowhere you need to run it at message object you want to delete

#

and the delay is a keyword argument

#

so you cant just do msg.delete(5) it has to be msg.delete(delay=5)

#

and your own message with command you ran you can find out in the ctx.message as the docs say:

The message that triggered the command being executed.

mild nimbus
#

can someone help me make a discord bot? for antinuke

slate swan
#

We can help you with your issues you face, we don't code for you

#

You need to await

naive briar
#

First, you didn't await the sends

#

Second, member will never be none

slate swan
#

And that try/except is a bit weird and pointless

naive briar
#

You made the member argument required

slate swan
#

How to block some people from using a discord bot command and blocking some inputs for commands [ the usernames and inputs should be editable without edditing bot code]

#

if you dont provide member it will throw exception

#

i think i can use pastebin for usernames and inputs [ most likely ]

naive briar
#

So, the member arg will never be None

slate swan
#

if you want it to be optional set None as default value

#

x: type = default

#

member: discord.Member | None = None

naive briar
#

You know, it's better to know basic Python before trying discord.py

slate swan
#

They've been told that lots of times but don't care a tiny bit worry_Nod

#

also there is a trick in python and you can use it like this:

member = member or ctx.author
``` which means member will be provided member and if its not provided ctx.author will be used instead
slate swan
grim robin
#

is there a way to retrieve the users of a forum channel?

slate swan
#

is there any basic template / code for making discord slash commands

#

need help with this ^

slate swan
#

check if the user has the role or not and change it depending on that

slate swan
unkempt canyonBOT
#

property members```
A list of thread members in this thread.

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be properly filled. Most of the time however, this data is not provided by the gateway and a call to [`fetch_members()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.fetch_members "discord.Thread.fetch_members") is needed.
hollow minnow
#

ุณู„ุงู…

grim robin
slate swan
grim robin
#

overall

#

the class does not support the members attribute

slate swan
#

then its based on permissions

grim robin
slate swan
slate swan
#

but its not as straight as accessing one attribute

#

if you want that you need to get list of all guild members

#

get their permissions and copare to desired channel

grim robin
#

I do know that. I was hoping I'd save using "for" loops or similar methods

slate swan
grim robin
#

in 20k+ servers that process can take some time

slate swan
#

yeah

grim robin
#

thanks for replying though. much appreciated

slate swan
unkempt canyonBOT
#

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

fading linden
slate swan
#

no there is no official library from discord but there is a list of libraries that** have valid rate limit implementations, are recently maintained, and have large communities of active bots.**

https://discord.com/developers/docs/topics/community-resources#libraries-discord-libraries

Discord Developer Portal

Integrate your service with Discord โ€” whether it's a bot or a game or whatever your wildest imagination can come up with.

fading linden
#

bless those who started these SDKs

#

there's DSharpPlus
stg devs are the best at naming things

#

there's even one in rust

slate swan
#

yeah but most of them are in python xd

fading linden
#

yeah no kidding

I'm curious what makes python so dang popular, not only that, but how fast we come up (by we i mean the devs who put the work in) with whatever's needed to transport something so that it's python friendly

#

its insane

slate swan
#

well python is just easy to operate

cloud dawn
#

I think the biggest turnover will be the fact it doesn't have strict types.

#

And no forced public static protected bool

#

Hence the reason AI is a lot in Python since it doesn't matter how fast the code runs it still needs to process it with the GPU, so the code will not be the bottleneck so they chose the most convenient.

proper thicket
#

so if i was trying to run both of my files i would put it in cogs folder right my main.py and bot.py

#

!cogs

#

!dcogs

#

question if my bot.py file is running my activity status only should i just change the name to activity.py

slate swan
#
@client.tree.command(name='slayer')
@app_commands.describe(username = 'Whats your Minecraft username', slayer = 'What Slayer', level = 'What level u want to see')
@app_commands.choices(slayer=[
    discord.app_commands.Choice(name= 'Voidgloom Seraph', value='Voidgloom'),
    discord.app_commands.Choice(name= 'Sven PackMaster', value='Sven'),
    discord.app_commands.Choice(name= 'Tarantula', value='Tarantula'),
    discord.app_commands.Choice(name= 'Revenant Horror', value='Revenant'),
])
async def slayer(interaction: discord.Interaction, username: str, slayer: discord.app_commands.Choice[str], level: int):``` i dunno it says application didnt respond
#

You're not responding in that code block. In fact, your function does nothing - it's just decorators and a function definition

slate swan
#

!paste it then

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
#

Don't know, can you?

proper thicket
#

can i get help with this error please?

slate swan
slate swan
proper thicket
slate swan
#

mange_messages is not a permissions

#

You have a typo

proper thicket
young pendant
slate swan
proper thicket
young pendant
slate swan
proper thicket
slate swan
slate swan
slate swan
slate swan
#

this one with options doesnt work for a reason

#

Doesn't prove anything

proper thicket
slate swan
#

Defer it and see if it works afterwards

#

how do u defer

#

await interaction.response.defer() at the top

#

its stuck on thinking..

slate swan
#

cause the other one without options works fne

#

fine*

#

p intrestng why my code dont work

#

Add an else branch

#

See if it goes there

#

Add some debug logs with print and check the flow it goes through

#

try the if statement

slate swan
#

You only have if/elif

#

Add an else at the bottom and most importantly print logs a bit everywhere and see how your code goes

#

the entire code worked when i was using normal bot prefixes

#

and i made another command it also worked with /

#

but this command has Choices soo it doesnt work

#

do i need to like register them or enabling anything for them to work

#

You need to register the slash command that's it

tidal folio
#

When I put it back 2 times
opens to

#

@slate swan sorry ping but look photos

slate swan
#

lemme like edit code rq

tidal folio
slate swan
tidal folio
#

Anyway Answer my problem

tidal folio
slate swan
#

????

tidal folio
#

Repeat

#

Look photo

#

Look game id

slate swan
#

Doesn't make any sense, sorry

tidal folio
#

what

slate swan
#

What you're saying doesn't make sense

tidal folio
slate swan
#

Yes I've seen that, so what's the issue

#

Just do everything like the first picture

tidal folio
#

Bruh

slate swan
#

And remove the code that produces the second picture

tidal folio
#

Wdym?

#

Seet_footer.

slate swan
#

Rewrite your code so that it produces the same as the first picture again

#

And otherwise without code it's hard to understand what you're doing and what is wrong as your English is not the best

tidal folio
#

Check photos

slate swan
#

without code it's hard to understand

tidal folio
slate swan
#

Dude stop spamming your pictures and give your code for once jeez

tidal folio
#

Wich send you

#

Bruh didn't spam

#

Can you fix my problem?

slate swan
#

SEND. THE. CODE.

tidal folio
#

WICH?

#

Waite

slate swan
#

Of your command what else

#

Oh lordy lord

tidal folio
slate swan
#

The ENTIRE code

#

Not just random parts of it

tidal folio
#

But if I don't, it won't work

slate swan
#

!paste your entire command code there

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
#

@slate swanhow to get the user id of the person who used a / command

#

interaction.user.id

tidal folio
slate swan
#

Not for slash commands, no

buoyant quail
#

Interesting that people always keep using good names ctx, inter/interaction even if they don't know python at all and their other variables are just random things. Never seen someone who uses another name

slate swan
#

Because people have seen it too many times

thin raft
buoyant quail
thin raft
#

or they get it from chatgpt

slate swan
#

But then they have lots of comments

young pendant
#

@slate swan sorry for the late response.

I have fixed the issue, can you answer me that?

https://paste.pythondiscord.com/oduxicaxit

I want the button to change the color from blue to green on interaction,

I also want the dropdown to change to green on interaction, how do I do that?

lofty lance
#

Hey someone free at moment

#

need little help

dawn adder
#

I don't understand how to do this with the Ranked Card. I have already watched a video (Video Link: https://youtu.be/3ktorz8QJTM), but I just can not figure out how I can do this best and understand. The command works, but I would like that when you enter /rank, that your data is displayed on a banner.

Current levelingcode: https://sourceb.in/7rkalJhyw5

Would be happy if someone would help me to understand it

tidal folio
thin raft
dawn adder
lofty lance
#

hey i am getting issue

#

on cogs

slate swan
#

exceptions and code

lofty lance
#
@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}           ({bot.user.id})")
    print("Bot is ready") 
    for cmd_file in setting.CMDS_DIR.glob('*.py'):
        if cmd_file.name != '__init__.py':
            await bot.load_extension(f"cogs.{cmd_file.name[:-3]}")
#

thsi is the code

#

i am folling a tut for it

#

my files to verify that its not locaiton error

#
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Start_comm' raised an error: TypeError: object NoneType can't be used in 'await' expression
#

this is the error

slate swan
#

can you print what cmd_file.name is?

lofty lance
#

u mean to print in code?

slate swan
#

no i said print cmd_file.name

#

what is under this varriable

lofty lance
#

ah ya so u mean to replace await stuff with print ?

slate swan
#

no i did not say to replace it

#

i just want to know whats under this varriable

#

whats so hard in doing print(cmd_file.name)

lofty lance
slate swan
#

no you said to replace it with await

#

i want you to put it above it

#

and show me what it prints

lofty lance
#

this u mean? right ?

slate swan
#

yes, can be

glad cradle
slate swan
#

anyone have any idea how one of these would be made where it updates itself in time of using a command to add and remove people from the q

lofty lance
#

alr let me hit run

#

perfectly fine ig

#

its printting what its suppose to

slate swan
lofty lance
#
from discord.ext import commands

# Create a new cog class
class StartComm(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # Command to start the bot
    @commands.command()
    async def start(self, ctx):
        await ctx.send("Bot is ready!")

# Setup function to add the cog to the bot
def setup(bot):
    bot.add_cog(StartComm(bot))
slate swan
#

The issue is in that start_comm file

thin raft
# dawn adder Yeah, but not for the bar

ok imagine the bar occupies 150px it starts at x = 100 and ends at x = 250
then, you'd need to calculate which % of the level is completed, for example, you have 20xp and need 100xp, so you're 20%.
Now you get the 20% of 150, it's 30, then you just make a rectangle (making it easy) that starts from x = 100 to x = 130

slate swan
#

and .add_cog must be awaited as well

lofty lance
#

ohhkee

lofty lance
#

@slate swan btw remeber code i showd u yesterdday in 3 files
i am planning to put it in this one start_command file
what u think good idea?

dawn adder
thin raft
tidal folio
#

@slate swan Sorry ping but can you answer this

#

Anyone know?

#

@thin raft

thin raft
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

thin raft
#

you've been asked to share your code countless times

#

if you don't provide code we wont be able to help :)

slate swan
#

Hello please help me but I won't share my code

#

Edit:

Hello please help me, these are a few random lines from my code but not everything because I don't want to

#

It's hard to help when someone doesn't read at all

#

You've been told countless times to share the ENTIRE code of your command

thin raft
#

this guy is nuts

slate swan
#

So maybe it's time to share the ENTIRE code for once

#

Maybe with this bold and underline style it'll be easier

#

for what are the code blocks lmfao

thin raft
#

proceeds to delete every message in existance

slate swan
#

LMAO

#

oh lordy lord, sometimes

torn solar
#
await member.add_roles(role)```
#

it said theres an error in the member file of python discord

#

when the role gets added can someone help me fix

sick birch
#
- role = discord.utils.get(member.guild.roles, id='1121191878063308821')
+ role = member.guild.get_role(1121191878063308821)
torn solar
#

line 1044 i think

sick birch
#

Can you show us the error?

#

Without the error I can only guess at the problem

torn solar
#

if it shows up again ill show you

#

but i dont have it rn

fading harness
sick birch
#

yes

fading harness
#

Omg

#

Can you do?

sick birch
#

No but I can show you how to

fading harness
#

Like if I comment this it will do this

#

To every message

sick birch
#

mmhm

fading harness
#

I saw someone with that

#

But he donโ€™t give me the code

sick birch
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your botโ€™s own messages and private messages are sent through this event. This can lead cases of โ€˜recursionโ€™ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
sick birch
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
sick birch
#

That's all you should need

fading harness
#

Hmmm

#

Ok Thx but idk abt python

#

Hum

sick birch
#

discord.py is an advanced library so I'd recommend getting comfortable with Python first

fading harness
#

Oh ok

#

I already did a auto send message bot

#

And auto send and delete at the same second for that servers that have level

young dagger
young dagger
#

Try it and see

fading harness
#

Where do I put the token

#

Im mobile now Iโ€™m only gona try tomorrow but tysm

young dagger
#

No problem

slate swan
#

Why isn't it pinging the actual role

#

is there a fix for this

thin raft
sick birch
tight fox
#

How do i add a command to my bots profile like this
I already have the slash command I want to add but I don't know how to make it show up on the profile

slate swan
#

I think that's a feature of verified bots

slate swan
#

It's automatically done for verified bots, nothing you can control

torn solar
#

discord module is installed so idk whats wrong can someone help

slate swan
#

The issue is pythonanywhere and a free account

#

just install Python on your device (or VPS) and you'll probably not have the issue anymore

torn solar
#

im trying to host a discord bot in the cloud

slate swan
torn solar
#

not trying to pay for one

slate swan
#

whatevs You'll struggle then, most free hosting services come with some sort of catch

torn solar
#

im fine if its trash cus the bot is small

#

and it doesnt have many features

slate swan
#

I'm currently with DigitalOcean and they've been great for me

torn solar
#

is it free?

#

i just need something free and 24/7 it can be trash idc

#

as long as it works im fine with it

torn solar
#

they make u link a payment method when u sign up

slate swan
#

It's a paid service. But they'll probably offer some sort of free trial if you want a taster

torn solar
#

im literally just making an order bot for a minecraft city roleplay server

#

where players can order items

#

so i dont really wanna spend money

slate swan
#

Most VPS providers have some sort of free plans with limitations, look at then

torn solar
#

im seeing if aws has it for free rn

#

why does oracle make the shadiest looking programs bruh

slate swan
#

You'll get banned when using Oracle's free plan

desert heart
slate swan
#

Ask people who tried it, they ban without notice nor reason(s)

#

You get banned for other things as well that are less resource eating than Discord bots

#

Forum posts, reddit posts, blog posts, ... you'll find countless people having such experience with Oracle

#

Though try it and see after some day(s) what happens CatJAM

#

Then make attempts at contacting their support, they will ghost you Pog

desert heart
#

That sounds odd, but I've never used them. My reasonable expectation was that they say "Here's this free thing. Here are the CPU, memory, networking, and storage limits. We don't care what you run, just don't exceed those limits."

#

Well, don't care within reason. Don't host some malware or whatever.

slate swan
#

Well that's what most people initially thought I guess

#

Until they got banned with no reason for hosting some harmless Discord bot or other thing

burnt island
#

discord bot newbie here - I see from the docs that I could use a Client or a Bot instance? How would I go about deciding which might be the better choice?

sick birch
burnt island
#

Ah! That was not obvious!! Thank you.

torn solar
#

I found some replit method with a web server that allows me to host it 24/7

#

is that reliable it uses uptimebot to ping the webserver every 5 minutes

#

and it keeps the bot alive

sick birch
#

Definitely not

#

Replit is not a hosting service

torn solar
#

it seems to be working so

#

๐Ÿคทโ€โ™‚๏ธ

sick birch
#

Right up until it doesn't

torn solar
#

for a small server so i think it will be fine

naive briar
#

Doesn't matter

#

It'll get rate limited someday

burnt island
#

What do people use for having various dev and testing versions of a bot? Create separate discord servers to invite those into? Use some sort of prefix on every command except production? Something else?

slate swan
#

Different bot in a testing server

sick birch
#

Or in the same server with a different prefix

burnt island
#

Thanks again

raw quail
#

guys i cant see a icon of embed. anyone have same issue with me or they updated to delete icon?

shrewd vapor
#

Hi, i need help please for send error in channel with webhook

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/otrobot.py", line 256, in delete_verification
    await interaction.followup.send(embed=embed_error)
  File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1800, in send
    data = await adapter.execute_webhook(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'delete_verification' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
raw quail
slate swan
#

Known issue, Discord is aware

shrewd apex
burnt island
raw quail
shrewd apex
#

possibly even set up permissions and roles checks for ur commands

slate swan
#

If you post there and 5 minutes later ask here, why not just ask here directly

shrewd vapor
#

Its my command:

@bot.tree.command(name = "delete_verification", description = "Delete verification and channel")
async def delete_verification(interaction, role_id : discord.Role):
    guild_id = interaction.guild.id
    guild = interaction.guild
    if (not interaction.user.guild_permissions.ban_members):
        await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
        return
    try:
        if database_verif.get_role_id(guild_id) is not None:
            database_verif.remove_verification(guild_id, role_id.id)
            if database_verif.get_role_id(guild_id) is None:
                channel = discord.utils.get(guild.text_channels, name="verification")
                await channel.delete()
                await interaction.response.send_message("The verification is removed successfully")
            else:
                await interaction.response.send_message("Error deleting verification")
        else:
            await interaction.response.send_message("The verification is not in place")
    except Exception as e:
            embed_error = discord.Embed(title="Error", description=f"{e}")
            await interaction.followup.send(embed=embed_error)

            webhook = "LINK_WEBHOOK"

            data = {
                "content": "@everyone",
                "embeds": [{
                    "title": f"Error disable_verification on {interaction.guild.name}",
                    "description": f"{e}",
                    "color": 16732345,
                    "footer": {
                    "text": "OtroBot"
                    },
                    "image": {
                    "url": "https://i0.wp.com/xboxera.com/wp-content/uploads/2020/08/XGPgamescom_inline1.jpg"
                    }
                    }],
                    "username": "Log Error OtroBot",
                    "avatar_url": "https://i.imgur.com/44N46up.gif"
                    }
            requests.post(webhook, json=data)```
#

First time i have error with webhook

tidal folio
slate swan
#

@bot.command()

#

And there's no ctx.response for prefix commands

tidal folio
shrewd vapor
#

ctx.send

slate swan
#

And you need message content intent for prefix commands

shrewd vapor
#

or ctx.reply

slate swan
#

!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. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

shrewd vapor
#

Krypton you know why Unknow webhook ?

slate swan
#

You should know though with all the commands that "you" made working

#

E.g. that command you've spammed with pictures and never shared code

slate swan
shrewd vapor
#

Yes but he is defined

slate swan
#

No

#
await interaction.followup.send(embed=embed_error)
#

You can't send a followup if you've never responded in the first place

#

So do like you did in your entire code, await interaction.response.send_message(embed=embed_error)

shrewd vapor
#

Yes i have take a mistake here

#

I try again

slate swan
#
lottery_message = await interaction.message.channel.fetch_message(message_id)

this is not working

discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

message-id is correct

shrewd vapor
#

Ok work thanks

slate swan
naive briar
unkempt canyonBOT
slate swan
#

And the message should be in that channel obviously

slate swan
#

Then it won't work

slate swan
#

get the channel object for the channel the message is in

#

fetch the message there

#

fetch channel? and then fetch message?

#

ok

#

Get channel, if it returns None then fetch channel

#

Then fetch message

#

Hard to help without the code

#
await ctx.send(title='', description='**:tick_red: | I Do not Have Ban Members Permission To Perform This Command**', color=0xe74c3c)

What is that

naive briar
#

Yes

#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
naive briar
#

There are no title, description and color arguments in the ctx.send method

fringe lake
#

is possible to get member instance from the id ?

naive briar
unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
fringe lake
#

thanks

#

btw is the "/" a second parameter ?

naive briar
#

No, it's there to tell Python that the arguments in front of it should be positional-only

fringe lake
#

oh ok thx

#

also may ask another question ? is user.discriminator property still working even after the username update ?

hollow osprey
#

it returns a 0, AFAIK

#

for people migrated over

fringe lake
#

i see, thx

slate swan
thin raft
#

!d discord.Role.edit

unkempt canyonBOT
#

await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the role.

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

All fields are optional.

Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.

Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
thin raft
#

change permissions

slate swan
#

i am trying to make a black jack bot

thin raft
#

then do the same but with channel

slate swan
#

alright

#

thx

thin raft
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
slate swan
#

ily

naive briar
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
thin raft
#

i've been doing it with edit all this time

fringe lake
#

what is asynciterator ?

thin raft
#

do you know what an iterator is?

naive briar
#

Iterator that's asynchronous

fringe lake
naive briar
#

no

fringe lake
#

something that you can do a for loop in

thin raft
#

those are iterables

naive briar
#

!e

print(iter([]))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

<list_iterator object at 0x7f4332604790>
naive briar
#

list and list_iterator are different things

naive briar
# naive briar Iterator that's asynchronous

!e it's like async generator but iterator

import asyncio

async def async_gen() -> None:
    for i in range(10):
        yield i

async def main() -> None:
    gen = async_gen()

    print(gen)
    print(*(i async for i in gen))

asyncio.run(main())
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | <async_generator object async_gen at 0x7f18b2f14790>
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 13, in <module>
004 |     asyncio.run(main())
005 |   File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
006 |     return runner.run(main)
007 |            ^^^^^^^^^^^^^^^^
008 |   File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
009 |     return self._loop.run_until_complete(task)
010 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
011 |   File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/wujoloyine.txt?noredirect

naive briar
#

Sounds about right

thin raft
#

!e

import asyncio

async def async_gen() -> None:
    for i in range(10):
        yield i

async def main() -> None:
    gen = async_gen()

    print(gen)
    print(*[i async for i in gen])

asyncio.run(main())```
unkempt canyonBOT
#

@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <async_generator object async_gen at 0x7fbba0134790>
002 | 0 1 2 3 4 5 6 7 8 9
thin raft
#

() doesnt make it a tuple im afaik

naive briar
#

It's for generator expressions

thin raft
#

wdym

naive briar
#

!e

print((i for i in range(10)))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

<generator object <genexpr> at 0x7f7df86e01e0>
thin raft
#

can you unpack a generator?

#

!e
print(*(i for i in range(10)))

naive briar
#

Yes?

unkempt canyonBOT
#

@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.

0 1 2 3 4 5 6 7 8 9
thin raft
#

im confused, why did it raise an error in the first code?

fringe lake
#

i think i need understand how asynchronous programming works

naive briar
#

Probably because it's using async for

fringe lake
#

i still dont understand it

naive briar
#

So it turns into async generator

fringe lake
#

thank you guys for the help

#

well, sorry im asking a lor but, what is the diffirence between .guild and .Guild

naive briar
#

discord.guild is a module, discord.Guild is a class

fringe lake
#

when i did ctx.Guild it said Guld is not an attribute of ctx

naive briar
#

Eh, I thought you asked about discord.guild and discord.Guild stuff

naive briar
unkempt canyonBOT
fringe lake
#

oh i see thx

#

but basically my problem is

naive briar
#

Well, the error is right

#

You can use list comprehension to collect them, the flatten method was removed

fringe lake
#

eh

#

the api is a scam then

naive briar
#

What api

naive briar
#

Eh, nextcord is a different library

#

discord.py doesn't do that anymore

fringe lake
#

oh

#

thanks ;-;

#

@naive briarbut can you consider Asynchronous Iterator as a list or something

#

how can i get the data inside it

naive briar
#

!list-comp

unkempt canyonBOT
#
List comprehensions

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if clause:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

naive briar
#

Just change for in to async for in

fringe lake
#

i know how list comprehenion works, but idont howt o apply it to that class

fringe lake
naive briar
#

Like

bans = [ban async for ban in guild.bans()]
fringe lake
#

and ban is a banentry right?

naive briar
#

Yes

fringe lake
#

thanks a lot again ;-;

lofty lance
#

hey guys i am having some issue in imporitng a cog
in discord.py
can anyone help out pls

lofty lance
slate swan
lofty lance
#

dont wana be like rude boss

slate swan
#

no cause you are not asking 1 person

#

when someone is free they are gonna answer here

#

if you send just the text saying you have issue they are most likely going to ignore it or dont even notice it

lofty lance
#

so its a quit

#

big error
in cogs stuff

slate swan
#

show it

lofty lance
#

e:\onepiece-bot\main.py:26: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension('StartComm')
Object allocated at (most recent call last):
  File "e:\onepiece-bot\main.py", lineno 26
    bot.load_extension('StartComm')
ERROR      - discord.client  : Ignoring exception in on_ready
Traceback (most recent call last):
  File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
    await setup(self)
  File "e:\onepiece-bot\Cmds\start_comm.py", line 10, in setup
    await bot.add_cog(start(bot))
  File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 770, in add_cog
    raise TypeError('cogs must derive from Cog')
TypeError: cogs must derive from Cog

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

Traceback (most recent call last):
  File "E:\onepiece-bot\onepiece\lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "e:\onepiece-bot\main.py", line 30, in on_ready
    await bot.load_extension(f'Cmds.{cmd_file.name[:-3]}')
  File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension 
    await self._load_from_module_spec(spec, name)
  File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cmds.start_comm' raised an error: TypeError: cogs must derive from Cog
E:\onepiece-bot\onepiece\lib\site-packages\discord\client.py:446: RuntimeWarning: coroutine 'Command.__call__' was never awaited
  await self.on_error(event_name, *args, **kwargs)
Object allocated at (most recent call last):
  File "e:\onepiece-bot\Cmds\start_comm.py", lineno 10
    await bot.add_cog(start(bot))
slate swan
#

show your start class

#

you are trying to load

lofty lance
#
from discord.ext import commands



@commands.command()
async def start(self, ctx):
        await ctx.send("Hi, I am ready!")

async def setup(bot):
    bot.add_cog(start(bot))

slate swan
#

.add_cog as the name says is for adding cogs not commands

#

you cant just put random thing in it and expect it to work

lofty lance
#

add commnad

#

should not use autocmmplete blindly

slate swan
#

there is something like .add_command but im not sure if this will work just create a cog and add this command into it

lofty lance
#

didnt work

#

how to create that cog now

slate swan
#

like you create all other cogs

#
class MyCog(commands.Cog):
    ...
lofty lance
#

ohh

#

kk let me try

slate swan
#

yes this should work

#

wait no

#

the Cog is uppercase

#

not lowercase

lofty lance
slate swan
#

did you change the cog to Cog

lofty lance
slate swan
lofty lance
slate swan
#

..

#

.add_command is for adding commands you are adding a cog

#

so use .add_cog

lofty lance
#
  bot.load_extension('StartComm')```
slate swan
#

you did not await the bot.load_extension

lofty lance
#

i did that fr

slate swan
#

yeah i dont see await there

#

and the error should tell you the line already

lofty lance
#

but the code never add it there

slate swan
#

but it is there

lofty lance
#

code from yt video

#

he hitted the run button and no error

slate swan
#

then ask the video owner

#

how it works

lofty lance
#
  bot.load_extension('StartComm')```
#

even if i add await

lofty lance
slate swan
lofty lance
slate swan
#

the error literally shows you the line why dont you go to this line and check it

slate swan
lofty lance
#

commands file

lofty lance
slate swan
#

add await before bot.load_extension

lofty lance
#

i have added that

slate swan
#

man can you read

lofty lance
#

there is a wait in commands .py see

vocal snow
#

read your error

lofty lance
vocal snow
#

which line is raising the error?

slate swan
lofty lance
slate swan
#

so go to that line

lofty lance
#

line 26

slate swan
#

can you send full traceback

#

and full code not as screenshot

lofty lance
lofty lance
slate swan
#

Or just read errors duh

lofty lance
#

done

slate swan
#

next time dont send errors when you see it occur just try to solve it and when you fail send it here

lofty lance
slate swan
#

The error was

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension('StartComm')
lofty lance
#

sorry got confused in file name too

slate swan
lofty lance
#

i will just dont copy the file name with funtions

#

lets generate some more erros now

tawdry tundra
#

Can I make something like channel.send but with discord account not in bot?

vocal snow
#

no

#

that's only possible via self-botting which is not allowed by discord

tawdry tundra
#

Request?

lofty lance
#

maybe ip too

tawdry tundra
#

What

#

Why its not only the token?

naive briar
#

Acktuarly ๐Ÿค“

lofty lance
slate swan
lofty lance
#

๐Ÿคฃ

slate swan
#

and stop being cringe about owo

#

Owo currency is pointless

lofty lance
#

well i get dm from my frnds too
make a self bot for me for owo

#

i am like

slate swan
#

jeez

slate swan
burnt island
vocal snow
#

it's a little outdated

slate swan
vocal snow
#

eg, the interaction and button parameters in the callbacks should be swapped

#

aside from that it should be fine though

slate swan
vocal snow
#

Actually some of the examples look incorrect to me

burnt island
#

right up there with import pandas as np

slate swan
#

xd

burnt island
#

If there's something better out there, just point me in the right direction!

shrewd apex
#

yeah the gist seems fine mostly view components itself are simple its more about how u handle the interactions the libraries have made pretty nice wrappers over the components

burnt island
#

Thanks all. As long as it's not me taking down some road I'll later learn to regret, that's fine for now.

slate swan
burnt island
#

So, definitely in learn rather than teach mode for now.

slate swan
#

even about buttons and other components

#

you can find it under views directory

shrewd apex
#

diskane ftw

slate swan
burnt island
slate swan
slate swan
#

but it exists!

shrewd apex
#

disnake has guides on their site

burnt island
#

Yep, now I know where to look there's some good stuff in there. Thank you.

slate swan
#

๐Ÿ‘

burnt island
#

No idea if something I've done is well known or not. Happy to write it up if it helps...
I have my bot running in a docker container with a github action to build an image for that and push it to the github package registry. My production box then just has a docker compose file to pull that (along with a .env file for a few variables) and nothing else.

#

The image also handles my local dev copy - production has the bot installed as a wheel, dev mounts the local source code folder into the container.

#

oh, and it's multi-platform - production runs on a pi.

slate swan
#

are you willing to share the compose file and the gh-action i was trying to do something like this but ended up logging in to vm and pulling the code from github and building docker image on vm directly

slate swan
#

no need to bump your post when its 1 message above

#

so wait

#

until somebody does help you

burnt island
slate swan
burnt island
#

A bot that currently does pretty much SFA (but at least does so successfully)!

slate swan
shrewd apex
slate swan
naive briar
#

Any errors?

shrewd apex
#

i dont have a vm so i didn't make the vm deployment part

burnt island
#

you can have a private package - in fact, it's the default

#

you have to jump through an extra hoop to make it public

#

even on a public repo

shrewd apex
#

that makes sense

slate swan
# shrewd apex dosent upload to registry for the one i made that would defeat the purpose of ha...

ah yeah then i already did the part with docker compose and github action but it did not built image it just pulled the code to vm and built it here

name: Deploy Discord bot
on:
  push:
    branches: [main]
  workflow_dispatch:
env:
  REPO_NAME: ${{ github.event.repository.name }}
  REPO_OWNER: ${{ github.repository_owner }}
  USER: down

jobs:
  push:
    name: Build & Push
    runs-on: ubuntu-latest
    environment: Staging
    steps:
      - name: Tag latest
        uses: appleboy/ssh-action@dce9d565de8d876c11d93fa4fe677c0285a66d78
        with:
          host: ${{ secrets.SSH_HOST }}
          port: 22
          username: down
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          passphrase: ${{ secrets.SSH_PASSPHRASE }}
          script: |
            cd /home/${{ env.USER }}/${{ env.REPO_NAME }}
            git pull
            docker compose build
  run:
    name: Run
    needs: push
    runs-on: ubuntu-latest
    environment: Staging
    steps:
      - name: Build Docker Image
        uses: appleboy/ssh-action@dce9d565de8d876c11d93fa4fe677c0285a66d78
        with:
          host: ${{ secrets.SSH_HOST }}
          port: 22
          username: down
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          passphrase: ${{ secrets.SSH_PASSPHRASE }}
          script: |
            cd /home/${{ env.USER }}/${{ env.REPO_NAME }}
            docker compose up -d
shrewd apex
#

ig I'll look into it when i deploy it

slate swan
#

thats a long code block

shrewd apex
#

i see

slate swan
#

which is not perfect

burnt island
#

That gh action is working nicely for me - just need to rename the production override file when you copy it somewhere

#

I might look at using multiple runners for the two platforms, but, with only two, it's not bad right now anyway.

lofty lance
#

Hey can i have a tip
like i am storign the sever data to be further used in game
so i make the user type start command and then i will store the server data
so what i want to do is
after teh server data is uploaded in my mongodb database
i want to disable the start command

so far what i have though of is
i am storign the guild id as _id in mongodb
so i have to check if that id do exitss
so that i cant be rund next time
or is there any way
that command can only be rund for once per server

fringe lake
#

guys can someone pls explain how he was able to get the "client" outside the class scope

fringe lake
#

the guy who wrote the code

#

the youtuber

slate swan
#

Ask that person

fringe lake
#

i cant ;-;

fading harness
#

hi how can i bypass this error

discord.errors.LoginFailure: Improper token has been passed.

slate swan
#

Comments exist

fringe lake
#

thats the main script

slate swan
#

Cool

fringe lake
#

like when i load the cog script, am i able to use the client variable in it ?

naive briar
#

Me when leaked token

fringe lake
#

bruh he regenerated it for sure

slate swan
#
client = commands.Bot(...)

average shit YouTube tutorials

#

One advice: Stop watching these tutorials

fringe lake
#

how can learn without them

naive briar
#

Examples, docs, ...

#

YouTube isn't the only way humans can learn from

fringe lake
#

well .... i dont understand shit in the api

#

i mean i get confused a lot of time when i read the docs

slate swan
#

That's why there are examples and guides

#

YouTube tutorials are outdated and usually showing bad coding

fringe lake
fading harness
slate swan
#

Google is your friend

#

The docs are your friend

fringe lake
fringe lake
slate swan
naive briar
fading harness
slate swan
fading harness
naive briar
slate swan
#

Make sure you've actually saved your file

#

And yeah, user tokens are not allowed

fading harness
slate swan
#

A great way to get your account banned ThumbsUp

fading harness
#

so i cant use my acc?

slate swan
#

You technically can, your account just may be terminated and banned from Discord, so don't do it

slate swan
#
import discord, os
from discord.ext import commands
from colorama import Fore, Style
from functions.json import JSONWrapper
from functions.console import *

config = JSONWrapper("config.json")
prefix = config.get("prefix")
token = config.get("token")

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

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

@bot.event
async def on_ready():
  cprint("INFO", f"{bot.user.name} ({bot.user.id})")

for filename in os.listdir("./cogs"):
  if filename.endswith(".py"):
    bot.load_extension(f"cogs.{filename[:-3]}")
    
bot.run(token)```

When I try !ping said ping is not found
fading harness
slate swan
#

Yes

slate swan
#

You read the error that says that load_extension hasn't been awaited

#

Then you can't use await outside of an async function so you create an async function to load your cogs

#

hen I puI cant

#
import discord, os
from discord.ext import commands
from colorama import Fore, Style
from functions.json import JSONWrapper
from functions.console import *

config = JSONWrapper("config.json")
prefix = config.get("prefix")
token = config.get("token")

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

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

@bot.event
async def on_ready():
  cprint("INFO", f"{bot.user.name} ({bot.user.id})")
  
  for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
      await bot.load_extension(f"cogs.{filename[:-3]}")
    
bot.run(token)```
#

Here again, reading will help

fading harness
slate swan
#

nvm i fixed it lol

#

yeah lmao sorry

naive briar
slate swan
fading harness
slate swan
#

Then invite the bot in the server

fading harness
#

i want to join in this acc

fading harness
slate swan
#

A bot must be invited in servers

#

To invite a bot you must have manage servers permissions

fading harness
#

ok so i cant do this

#

but ty

fading harness
lofty lance
#

i mean real ids tokens

fading harness
slate swan
#

You're late my guy

lofty lance
#

ig yes

fading harness
lofty lance
#

-_^

#

sus

slate swan
#

You get your bot token from the screenshot you've put above

fading harness
#

oh yea

slate swan
#

If you can't invite the bot in the server there is no point, that's it

naive briar
#

๐Ÿˆ

lofty lance
#

wait bro didnt did the set up of bot properly ig

#

-_^

slate swan
#

didn't did

#

Define "this"

fading harness
#

auto react

slate swan
#

Yes, you will get your account banned

fading harness
#

ok ty for the information

slate swan
#

Hey i need to know the code what customize a discord bot's Bio please ๐Ÿ™

lost dove
slate swan