#discord-bots

1 messages Β· Page 382 of 1

jaunty cape
#

this in the main Python file?

#

Oh in that case just await your fricking add_cog function

fast osprey
#

(you can also have external files that aren't extensions)

fast osprey
#

Yeah basic python rules apply. You could very well declare a class (a cog) in another file and import it just as normal. Extensions are purely optional

wispy falcon
#

doesnt work

fast osprey
#

Will need more detail than "doesn't work"

#

what you tried, what happened

wispy falcon
fast osprey
#

Show your code now

#

Specifically where you are adding the cog

earnest ginkgo
#

I don't want to interrupt the current conversation, could someone let me know when they're free to help please

jaunty cape
#

don't ask to ask

earnest ginkgo
#

what do you mean?

jaunty cape
#

you're asking to ask right now

#

you have to ask for the solution to your problem directly

#

i shouldn't even need to explain what i mean

earnest ginkgo
#

I will, I just don't want to take the attention away from someone else

jaunty cape
#

can you just ask really quickly

earnest ginkgo
#

alright then

#
Error handling request
Traceback (most recent call last):
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\web_protocol.py", line 452, in _handle_request
    resp = await request_handler(request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\web_app.py", line 543, in _handle
    resp = await handler(request)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\chris\OneDrive\Programming\misc\discord_bot_server\main.py", line 48, in send
    await my_channel.send(content="meow")
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
    data = await state.http.send_message(channel.id, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 638, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\client.py", line 1197, in __aenter__
    self._resp = await self._coro
                 ^^^^^^^^^^^^^^^^
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\client.py", line 507, in _request
    with timer:
  File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\helpers.py", line 715, in __enter__
    raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
```I don't even know where to start with this
jaunty cape
#

you see this? we wouldn't be having that conversation if you just asked

#

yeah i don't know anything about aiohttp

#

Solstice can most likely help

jaunty cape
#

can you send the code around line 57

jaunty cape
wispy falcon
earnest ginkgo
wispy falcon
jaunty cape
#

bro you can just say "it doesn't work" and expect people to

#

...

earnest ginkgo
wispy falcon
jaunty cape
# wispy falcon

you have to do that in a function, preferably setup_hook in the main python script

fast osprey
#

You shouldn't be adding the cog...inside of itself

wispy falcon
#

i tried adding it outside

jaunty cape
wispy falcon
jaunty cape
#

can you just add that line to the setup_hook function

#

!d discord.ext.commands.Bot

earnest ginkgo
# jaunty cape what is the request parameter doing there?

the thing I'm trying to do that doesn't work is this. a thread is running a discord.py bot, the main thread is running an aiohttp server. when a http request is sent to the server, it calls the send function with the relevant request object. it tries to send a message and then... blows up for no good reason.

unkempt canyonBOT
#
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.

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

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

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2\.0\.
fast osprey
jaunty cape
earnest ginkgo
jaunty cape
#

i still do really hacky code such as using Optional params so i don't have to do error handling πŸ’€

earnest ginkgo
#

my friend wanted a website that can control their discord bot. i don't see how else i'm supposed to link the two without having them be in the same process

#

it's not like i can communicate between processes over a local network because well... the entire obstacle here is that the discord process doesn't have a web server

#

it can be janky, i just want to get around this error

fast osprey
#

They do not have to be in the same process to communicate. This is the whole idea behind IPC

earnest ginkgo
#

what's IPC

fast osprey
#

Interprocess communication

earnest ginkgo
#

that's way beyond anything i'm capable of

#

i code in python lol

fast osprey
#

You can do IPC in python. It's just a concept

#

just like lists, or functions

earnest ginkgo
#

eh, maybe you can

fast osprey
#

So what is the web server doing, what is the bot doing, and what do they share

earnest ginkgo
#

all I am trying to do is just make a demo script

#

web socket receives request, makes bot do something

jaunty cape
#

πŸ‘

wispy falcon
#

alr

fast osprey
#

You don't even need to run a gateway bot to do that then

earnest ginkgo
#

wydm

fast osprey
#

Your web server can just do it

#

hit the discord api

earnest ginkgo
#

can't

#

I need to build something on top of an already existing discord.py bot

fast osprey
#

What about what you're trying to accomplish necessitates that?

jaunty cape
#

I need this guy's English skills

earnest ginkgo
fast osprey
#

The end goal is to receive request, do something. It going through a discord.py bot is an implementation detail, not a goal

#

You can do that if you really want to, though it should be through IPC

earnest ginkgo
#

long-term goal: friend has a big discord.py bot that they want to build a web panel for
short-term goal: receive a request and then do something with discord.py as a proof of concept

sick birch
#

can you give a specific example of "do something"?

earnest ginkgo
sick birch
#

web panels are common, but i find that for a lot of cases you don't actually need a gateway connection (and discord.py, by extension)

#

you can send messages without discord.py, relatively trivially

fast osprey
#

Yeah that could very quickly be done with a webhook

earnest ginkgo
#

why is it your goal to tell me i'm a liar instead of actually helping me

sick birch
#

i'm assuming you're looking for something like a texbox and a button on a webpage that sends a message via the bot

sick birch
#

in software development there's usually more than one way to go about doing something and the context and situation call for different solutions that may be more optimal than others

jaunty cape
sick birch
#

Huh?

jaunty cape
#

nvm i didn't say that

sick birch
jaunty cape
fast osprey
#

There is a pretty common phenomenon called the XY problem, where folks believe that the help they need is implementing the solution already in their head (X) rather than questioning it and taking a different approach entirely to the core goal (Y). To accomplish the material behavior you described, in order of what I'd recommend:

  1. Have the webserver internally do as much as it can, including communicating with the discord API
  2. If a gateway discord.py bot must be involved, have the webserver minimally communicate with it through some form of IPC and run these in separate processes
  3. Host both of these in the same process, where you will incur avoidable instabilities and maintenance problems. This would be done by attaching an asyncio-friendly web framework to the same asyncio event loop
earnest ginkgo
#

surely you should at least respect someone's wishes and help them with X, given they probably have their own reasons for doing so, rather than patronise them by assuming they have no idea what they're talking about and must be an idiot who actually means Y

jaunty cape
jaunty cape
fast osprey
#

Nobody said you have no idea what you're talking about. Us suggesting other things isn't that

#

People are wrong all the time and it's not a slight on their character. I'm in 11 years of industry experience and I get other solutions suggested to me all the time

jaunty cape
#

oh

#

no wonder this guy is so good at reading documentation

fast osprey
slim bloom
#

Why when I try to put the status of my bot online on Mobile it doesn't work?: ```py

source_ = source(discord.gateway.DiscordWebSocket.identify)
patched = re.sub(
r'(['"]$browser['"]:\s?['"

#

source_ = source(discord.gateway.DiscordWebSocket.identify)
patched = re.sub(
    r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
    r"\1Discord Android\2",
    source_
)

loc = {}
exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)

discord.gateway.DiscordWebSocket.identify = loc["identify"]```
#

@fast osprey

slate swan
#

Can I please get a link to a tutorial on how to get started making Discord Bots? For complete beginners. Also for discord bots do I need to learn about async and concurrency?

merry cliff
#

@slate swan ^

slate swan
#

Thanks!

mild token
#

When i group commands it don't show the sub command in server setting integration

#

It only shows the parent command is there any way to fix it?

#

Without removing the group

#

I want to lock commands with different roles

#

Another question I would like to ask is there any event which tells when the invite count increases?

fast osprey
#

Command groups are the level of permissioning. If you want to permission commands differently, they shouldn't be in the same group

normal lava
#

I am thinking to build a bot any one want to collab with me ?

glad cradle
marble rampart
slate swan
glad marsh
#

when uploading to a hosting server should i upload the py cache files?

#

or can i delete those?

slate swan
#

pycache can be deleted, it's cache as the name suggests

opal vortex
#

many people prefer uploading pyc inside of zip file to your application though when doing to a server

#

(with optimizations)

#

as long as said zip file is properly appended to sys.path.

finite salmon
#

I think the pycache will be rebuilt if the server has a different os than local machines os

fast osprey
#

So you somehow know how long it will take to make but are unwilling to do it yourself

delicate canopy
#

someone know how could i make the bot add a reaction to his embed right after saying it?

fast osprey
#

Is this for the purposes of people adding to that reaction to drive logic?

delicate canopy
#

yup

fast osprey
#

I'd recommend you implement this with ui buttons rather than reactions

delicate canopy
#

hmmm

#

never tried using those, its easier?

fast osprey
#

IMO the code is much cleaner on the handling side

#

If you're using discord.py, you can go to the repo and the examples/views folder

slate zephyr
#

anyone know how to get max file size upload for discord bot attachments, i know its usually 25mb but sometimes it can be increased with boosts or something so is there a way to get actual max upload size

#

i do have a method if the file is too big but I prefer using discord attachments

fast osprey
#

!d discord.Guild.filesize_limit

unkempt canyonBOT
primal pilot
#

I have a View where the user responds with a button. I'm trying to defer and then edit the embed in the message, but it sends a new message when I try to followup? How can it be made to edit the original message?

fast osprey
#

followup is for sending new messages

#

you can defer (non thinking) + edit_original_response

primal pilot
#

Ah, thanks!

primal pilot
#

If I want a database (a class instance of a custom Database class) to be available to all commands, is there a standard way of doing that in discord.py?

hushed galleon
#

you could also write Context[Bot] and Interaction[Bot] to typehint ctx.bot and interaction.client respectively, in case you find yourself only having those available

#

iirc for Context you can override Bot.process_commands() and use the Bot.get_context(cls=) parameter to replace it with your own subclass, but interactions don't have an equivalent method, so it's probably best not going that route

finite salmon
#

I personally just have a separate database class and use that class everywhere instead of passing it through bot so that I can interact with the database in places where the bot instance isn't available / has to be explicitly be passed.

I have the db connection object as a class attribute and it's set up when the bot starts instead of having it as an instance attr

primal pilot
#

Hmm, ok

#

Sounds like it's Singletonin' time

fast osprey
#

You can just attach something to the bot instance and then just access it anywhere you have the bot (which is pretty much anything in your application)

slate swan
#

Do you people do CI / CD for your discord bots?

primal pilot
fast osprey
#

Same way you attach anything to any object. Just something.whatever = something_else

opal vortex
slate swan
#

I do have a question that is more so out of curiosity rather than anything else. What's a discord bot you think is very complex to build and that would be impressive if you saw someone actually implement it?

sick birch
#

no tests (:P) or CD

slate swan
#

thanks

sick birch
#

mine is deployed in kubernetes so CD would probably be a whole thing to work out

#

though i hear good things about argoCD...

slate swan
sick birch
#

hence why we have stuff like docker that abstracts it out

slate swan
#

i need someone to help me

sick birch
#

you should ask your question then

slate swan
#

need help making custom web hook bot

exotic hazel
sick birch
slate swan
exotic hazel
#

So maybe having the bot interacting with databases or APIs? I'm a beginner, I don't know what other interesting backend things are there

sick birch
mild token
#

is it possible to upload image on role with memory buffer?

hushed galleon
#

sure, according to docs Role.edit(display_icon=) simply takes a bytes object

spiral kiln
#

How do i make my discord bot detect if the command was sent with a file attached?

spiral kiln
sick birch
spiral kiln
#

prefix

spiral kiln
sick birch
unkempt canyonBOT
sick birch
#

gives you a list of attachments in a message

#

however i believe you can use it as a typehint argument

hushed galleon
#

^ if its discord.py, you can add a parameter typehinted with discord.Attachment to automatically retrieve it for you

sick birch
#

hmm...

#

i am doubting myself now

hushed galleon
sick birch
#

huh. maybe that needs a docs change?

hushed galleon
#

hmm yeah probably an oversight, wasnt included in changelog either

spiral kiln
sick birch
#

can you show us your code and the error that was generated?

spiral kiln
#
@client.command(pass_context = True)
async def download(ctx):
    if not str(ctx.attachments) == "[]":
        #file downloader here
        await ctx.reply('File downloaded.')
    else:
        await ctx.reply('Attach a file to download.')
hushed galleon
#

if you want to check the attachments, you should access the message from the context object first with .message, then get the .attachments from that

spiral kiln
#

ctx.message.attachments ?

hushed galleon
#

yup, like: ```py
if len(ctx.message.attachments) < 1:
return await ctx.reply("Please upload an attachment!")

first_attachment = ctx.message.attachments[0]
... ```

#

as for downloading the data of the attachment, you can pick from .read(), .save(), and .to_file(), depending on what you intend to do with that data afterwards

spiral kiln
#

i intend to save it to a folder

hushed galleon
#

in that case .save() would be the most convenient method

#

!d discord.Attachment.save

unkempt canyonBOT
#

await save(fp, *, seek_begin=True, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Saves this attachment into a file\-like object.
hushed galleon
#

ergh, that doesnt mention it accepting a filepath

#

well you could either open a file first or pass the filepath as a string, as in: ```py
with open("my_file.png", "wb") as f:
await attachment.save(f)

or:

await attachment.save("my_file.png")```

#

Attachment also has a .filename attribute defined by the uploader if you want to use that

spiral kiln
#

would something like this work

hushed galleon
#

with proper quoting and formatting sure

#

using str() on an Attachment gives you the url though, not its filename

#

do you use vscode or pycharm? an editor with type checking and autocompletion would help a lot in writing your command

spiral kiln
#

i use vscodium so yeah

hushed galleon
#

hmm, in your case i think you can get the basedpyright extension as an alternative to microsoft's pylance

spiral kiln
#

ok ill install it

hushed galleon
#

in the settings you should be able to change the "Type Checking Mode" to basic or standard if you find the default is too aggressive/noisy

#

at least, it should warn you of syntax errors and undefined variables or methods

spiral kiln
#

ok thanks :D

#

i gtg

#

see you later

#

Thanks for the help :D

mild token
mild token
#

!d discord.Role.edit if display_icon is not supported by guild will it raise error or just become None?

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) 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...
golden portal
#

probably error discord.Forbidden?

#

i mean gotta try

mild token
#

Or is there any efficient way?

golden portal
primal pilot
spare pilot
#

Bro I need help

spare pilot
#

I was following the tutorial how to implement chatgpt in a discord not.

unkempt canyonBOT
#

src/bot/bot.py lines 57 to 61

def __init__(
    self: Self,
    dragonfly_services: DragonflyServices,
    *args: tuple,
    **kwargs: dict,```
sick birch
#

so the linter knows the type when it's set

#

i think this may have been mentioned but making a global instance and importing it around will also work

normal lava
turbid condor
normal lava
#

But I m too much confused

mild token
#

is it possible to automatically add image to role with file?

quick gust
#

wdym by "automatically" and "add image to role"

mild token
#

to a role

finite salmon
#

that explains nothing

mild token
trim oriole
#

how to remove thumbnails from Embeds

#

i want to remove my gif thumbnail on a condition

finite salmon
mild token
unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

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

Changed in version 1\.4: Passing `None` removes the thumbnail.
mild token
#

this will remove the thumbnail

quick gust
#

I mean, I inferred they meant they want to remove the thumbnail after sending the message, in which case they will need to edit it too with an embed with no thumbnail

outer violet
#

how do i send the user a dm saying that theyve been kicked from the server? i use discords built in kick command, not a custom kick command

code: https://pastes.dev/GmER1VLPFB

its in hikari-py

#

i tried making my code work but it says it cant dm the user

fast osprey
#

You can't dm users who don't share a server with the bot. It is also against tos to dm users who have not explicitly asked you to

outer violet
#

?

#

its not against tos for a discord bot to send a user a dm saying that theyve been kicked from a server lol

fast osprey
#

It is against tos to dm a user who has not given you permission to

#

Sorry, developer policy.

  1. Do not contact users on Discord without their explicit permission.
smoky patrol
#

how can i send a local image to discord using discord.py in the embed

heady tree
fast osprey
#

The onus should not be on users

flat solstice
#

Hi so I've made a command with two args, of "ticket" and "name", that lets ppl move channels but for some reason it won't work when omitting the "ticket" arg when used n the context channel

@commands.bot_has_permissions(manage_channels=True, manage_roles=True)
@checks.in_database()
@checks.is_mod()
@commands.guild_only()
@commands.command(description="Move ModMail ticket to new category.", usage="moveticket <ticket> <name>")
async def moveticket(self, ctx, ticket: discord.TextChannel=None, *, name: str):
    ticket = ticket or ctx.channel

    if checks.is_modmail_channel2(self.bot, ticket) is False:
        await ctx.send(embed=discord.Embed(description="That channel is not a ModMail ticket.",colour=self.bot.error_colour,))
        return

    async with self.bot.pool.acquire() as conn:
        res = await conn.fetchrow("SELECT category FROM categories WHERE name=$1 AND guild=$2", name, ctx.guild.id)
        if res is None:
            await ctx.send(embed=discord.Embed(description="The name provoded doesn't match any ModMail category.",colour=self.bot.error_colour,))
            return
        
    category = ctx.guild.get_channel(res["category"])
    try:
        old_category = ticket.category
        await ticket.edit(reason = f"{ctx.author} moved ticket {ticket.name} from {old_category.name} to {category.name}",category=category,sync_permissions=True)
        await ctx.send(embed=discord.Embed(description="The ticket was moved successfully.", colour=self.bot.primary_colour))
    except discord.Forbidden:
        await ctx.send(embed=discord.Embed(description="Missing permissions to move the ticket.",colour=self.bot.error_colour,))

I thought maybe discord.TextChannel was having an issue (I am using dpy 1.5 after all) So I changed it to the following but that hasn't worked either

async def moveticket(self, ctx, ticket: int=None, *, name: str):
  try:
      ticket = ctx.guild.get_channel(ticket)
  except discord.NotFound:
      ticket = None
  
  if ticket is None:
      ticket = ctx.channel
  
  if checks.is_modmail_channel2(self.bot, ticket) is False:
fast osprey
#

anything less than 2.0 isn't supported, and will get api outages

flat solstice
#

i'm aware πŸ˜„ the 16 odd bots I have running on this version haven't seen any major issues.

I'm just not sure why it's not able to make the ticket arg optionable

fast osprey
#

There are literally api blackouts where it won't respond

#

That should concern you more than one specific command not working sometimes shrug

#

Anyways, a little debugging to identify the line that's not behaving like you expect would be useful

flat solstice
hushed galleon
flat solstice
hushed galleon
#

sure, Optional + your reassignment at the start of the command would be fine for that

flat solstice
#

I thought ...=None would have been making it optional?
I'll add optional to it when I'm next at the laptop and feed back on my result

hushed galleon
#

the difference is subtle, but only Optional allows the parameter to be skipped during dpy's parsing

#

just writing a default value doesn't have the same effect

fast osprey
#

= None does make it optional. The Optional typehint is, well, optional

hushed galleon
flat solstice
#

I always thought it did

fast osprey
#

Step one in debugging would be to log the parameters you are getting to make sure they are what you think they are

mild token
#

is there any method which takes invite code and retrives the full invite link?

sick birch
#

discord handles redirection

final breach
#

Hi here
im using discord audit log to log im text channel but moderator action are not showing
i did try this

@commands.Cog.listener()
    async def on_audit_log_entry_create(self, entry: discord.AuditLogEntry):
        async def default_handler(entry):
            pass
        print(f"New audit log entry: {entry.action}")

but nothing printing out

#

in doc its says that i need This requires Intents.moderation to be enabled.
but when i do intents.moderation = True
i get AttributeError: 'Intents' object has no attribute 'moderation'
im using intents = discord.Intents.default()
and i did try using all and none

fast osprey
#

What version of the library are you on?

final breach
#

latest

fast osprey
#

Which is?

final breach
#

2.1.0

fast osprey
final breach
#

Requirement already satisfied: discord.py in c:~\python\python311\lib\site-packages (2.1.0)
when i try to update

fast osprey
#

How are you trying to update?

final breach
#

pip install

fast osprey
#

What's the full line?

#

(fwiw, this event was introduced in dpy 2.2.0)

final breach
#

thx for ur time

gusty patio
#

can someone help me how i can make bot to give roles when someone writes one message in verifiy channel?

#

thanks guys

fast osprey
#

What are you verifying by doing so?

gusty patio
#

so for an example user join server and i leave one channel and its verifiy

#

and when he writes something there he get role

#

and then with role he get acess to other channels

fast osprey
#

Right, but what is that message intending to verify? That they've read rules?

#

There are native onboarding tools that would be more appropriate for that

pseudo matrix
#

Please tag me if anyone knows the answer ^^

fast osprey
#

Audio receive is unstable and not supported by the library (or discord itself)

warm jay
#

hello, I want to make a discord bot using python. I need to somehow install discord.py but can't understand how. I tried some things but nothing works, please help me with that.

fast osprey
#

What did you try and what happened?

warm jay
#

I'm watching a video and the guy there types pip install discord.py
when I try to run this command it gives me syntax error in "install"

#

And I have checked pip when installing python

fast osprey
#

I firstly recommend you stop watching videos, they are notoriously bad

warm jay
fast osprey
#

If you're running on windows, just running pip x isn't ideal since it's ambiguous what python environment this runs against if pip is even on PATH at all. It's recommended to use the py launcher for everything python related

#

Either that or run everything within a virtual environment (preferred but more setup)

warm jay
#

I also have visual studio

#

and python on it

fast osprey
#

Python is on your system. Visual studio just runs against a specific installation if you hit run

#

But if you type pip x, you still run into exactly what I described

warm jay
#

python launcher? what's that? I think it was installed with python but I'm not sure what that is exactly

pseudo matrix
fast osprey
#

py launcher. Literally just typing py on your terminal/command line

#

Ex py -m pip

#

This should be an option when installing python on windows and it's highly recommended as python environment management without it is ass

warm jay
#

it says invalid syntax under pip

fast osprey
fast osprey
warm jay
fast osprey
#

Where are you typing this? What happens if you just run py?

#

This is a command you'd put in a terminal. Not python code

turbid condor
warm jay
fast osprey
#

Yeah this looks like a python interpreter

#

If you want to run py, that's just done in a raw terminal

#

Not within the python interpreter itself

warm jay
#

yeah thank you very much, now it works

hearty bobcat
#

@fast osprey can u help me

fast osprey
#

I'm sure lots of people listening could as well

solar bone
#

yo

#

can anyone help?

fast osprey
#

Feel free to ask your question(s) and if anyone knows the answer they will

solar bone
#

they wont import for some reason

hearty bobcat
#

How to make bot when user join the server he must write one message in verify then he gets role

fast osprey
#

I would suggest you use the built in onboarding tools if you want users to acknowledge rules or ensure they've read something

fast osprey
hearty bobcat
#

@fast osprey can u help me to do it free? somewhere

turbid condor
fast osprey
#

You can do that with the onboarding tools, that's a built-in "task"

hearty bobcat
#

i have no clue

turbid condor
#

Then that's a dead end

hearty bobcat
turbid condor
#

Well even for explaining you would need to have at least a beginner level understanding of python

fast osprey
#

I strongly suggest you start with exploring the onboarding tools already available to you

hearty bobcat
#

its a thing that i make code put id channel token of bot and run the code or?

#

and i heard something that u need to host bot somewhere hosting ig

turbid condor
turbid condor
#

I'd say take a few courses of python

#

It's pretty easy to learn

hearty bobcat
fast osprey
#

Depends entirely on the resources the bot requires

hearty bobcat
#

@fast osprey @turbid condor @client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'give me admin':
role = get(message.guild.roles, name='role')
await message.author.add_roles(message.author, role)

#

like this?

fast osprey
#

🀨

#

Yeah wanna explain how the onboarding tools don't accomplish this

hearty bobcat
# fast osprey 🀨

yh shit is pretty hard i would appreciate if someone could make it work for me because i really need this today and i dont know how to do it

mild token
#

what if i want to remove two roles from user and 1 role is present 1 not on user will that erorr out?

#

how can i know which role got removed?

#

from user.remove_roles?

slate swan
#

Look at the audit log or compare the member roles before and after

slate swan
slate swan
finite salmon
mild token
finite salmon
#

Yeah, see if the roles you're trying to remove exists the member, if it exists means that role is removed, if it doesn't exist that role isn't removed from the user

jovial heath
#

Sup

spiral kiln
#

Can someone tell me how to correct this code?

voice = discord.voice_client.VoiceClient
source = FFmpegPCMAudio(dir_path + sound)

player = voice.play(source)
#

Im trying to play an audio file.

#

i didnt forget

from discord import FFmpegPCMAudio
#

btw

#

i just dont know what to put before .play()

#

as voice

#

Fixed

#

I have a question, how do i get the voice channel that the discord bot is in?

spiral kiln
#

solved.

spring rampart
#

how can i add error handling to my bot's ban command??

#

like i dont understand how you could do like if the discord.Member is None but also the modreason

#

im so bad at python so if someone could help me i would greatly appreciate it

fast osprey
#

What is this ban command doing? Is it just a wrapper over a person manually banning a single user? If so, you should really consider not implementing this as you are actively reducing the security controls on the ban command that already exists natively

spring rampart
#

no error handling??

fast osprey
#

I'm suggesting you don't have this command at all as it is actively harmful to users

spring rampart
#

hmm

#

wait why is it harmful??

#

wdym

fast osprey
#

There is a native /ban in the client already. It has security controls that I guarantee your implementation does not

spring rampart
#

so are you saying don't do a ban command or jus don't do the error handling

fast osprey
#

I am suggesting you don't make a command that only exists to replicate what already exists but less secure

spring rampart
#

hmm i never thought about it that way

fast osprey
#

There are cases where you would have a more complex bit of logic over banning, but a direct "I run command person gets banned" is not that

spring rampart
#

ig yehh

fast osprey
#

The main reasons why you wouldn't want to do this are audit log hygiene and 2FA requirements, which bots really don't have a good way of replicating

dense falcon
#

is there a way I can sync my bot's commands to 2 or more servers without syncing globally or being rate limited?

quick gust
#

!d discord.app_commands.CommandTree.sync I think this has a guild parameter

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
wanton current
#

remember that the command also needs to have the same guild set

minor goblet
gleaming inlet
unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

minor goblet
#

Cool thanks

dense falcon
fast osprey
#

Have you gotten rate limited?

dense falcon
#

no, i havent tried it

fast osprey
#

There is very rarely a case where you would want to sync a command to multiple guilds but not all

dense falcon
#

syncing a command globally takes a few hours doesnt it?

fast osprey
#

Nope

sick birch
#

i believe it used to but it doesn't appear to anymore

fast osprey
#

Has been a year+ since it's been noticeable

dense falcon
#

oh, something wrong with when i synced it then probably since I still havent had them show up πŸ€” ill just need to do some fixes to the code then thanks

fast osprey
#

Two very important debugging tools:

  • sync() returns the list of commands that got synced
  • the integrations tab on a server will definitively tell you what commands are on a server, sometimes your client will lie
dense falcon
#

oh awesome thanks

#

So I fixed the sync and the commands show in the Integrations tab; do I need to wait longer to see them in chat? they dont show up with autocomplete

fast osprey
#

Refresh your discord client (ctrl + r)

dense falcon
#

tyyyy

minor goblet
gleaming inlet
gleaming inlet
# minor goblet

that line is not supposed to be in your code. You're supposed to run that in your terminal. Outside of the code

minor goblet
#

Oh... sorry just getting started

#

thank you

#

Fixed

mild token
#

All raw event uses caching?

fast osprey
#

The opposite, the whole idea of raw events is that they're independent of the cache and just give you the raw payload

glad marsh
#

I was wondering how I can make a check to see if a channel is a ticket channel

sick birch
glad marsh
sick birch
#

probably discord.py, just because it's got the most community support so it's easy to find help if you need it. you're free to use something else that suits your project though

snow coral
sick birch
#

what makes you say something is wrong

snow coral
#

When I’m using the limit parameter it’s responding with a actual number but when i use the after parameter it’s responding with 0

fast osprey
#

I mean we don't know what's in that channel, it might be helpful to do some logging in that loop to see what's actually happening

#

If you're using a channel as a database, I strongly recommend you use an actual database anyways

lucid ember
#
    if msg.content.startswith('hello'):
        print(msg.content[2])```

I need this to print out the second statement after `hello -> world <- This`
So I tried doing `msg.content[2]` to get the line of text after the first space, but seems that python does not work like that, and instead of giving me what I looked for it printed `e` (the e inside hello).

Can someone help me figure a way to do this? Thanks.
fast osprey
#

If youre using discord.py, I highly suggest you use the command framework for reading messages and parsing inputs

lucid ember
#

Why?

fast osprey
#

Because it takes care of the parsing for you

#

And makes your code far more readable

lucid ember
#

Do you mean the @bot.event / command() thing?

fast osprey
#

The command specifically yes

lucid ember
# fast osprey The command specifically yes

I'm using the 'event' for checking messages. I didn't write it above, but I have it in my code.

@bot.event
async def on_message(msg):
    if msg.author != bot.user: return
    if msg.content.startswith('$with'):
        print(msg.content.endswith)```
fast osprey
#

I would recommend you do this with a command

lucid ember
#

Ok

fast osprey
#

And not use on_message at all

lucid ember
#

Because it will check all messages sent in the server?

#

Oh that would actually solve the issue because I remember bot.command() makes it easier to check the message's content without the trigger

fast osprey
#

Because it interferes with the command logic

lucid ember
#

Yeah, thanks.

zinc gust
#

Shard ID None session has been invalidated.

#

anyone know what can cause this error ?

#

as my wifi is not bad idk how to fix

mild token
#

i want to load one cog only if bot is ready

sick birch
mild token
#

what should i use?

#

one cog has lots of listners

sick birch
#

do you know how to use cogs?

mild token
sick birch
#

so just do that

mild token
#

i just want to make the cog wait

#

until bot becomes ready

#

then load it

#

is their any method which holds the cog initilization until bot becomes ready?

sick birch
#

why does your cog need to wait for bot to be ready?

#

you said it was all only listeners?

mild token
#

so if cog wait until bot gets ready then it can solve the issue

sick birch
#

i'm not understanding, this doesn't seem like something that's dependent on your bot being ready

#

i am not able to use that instance bcz cog load before that
i dont understand this part

#

oh are you contacting the API in on_ready?

mild token
# sick birch i'm not understanding, this doesn't seem like something that's dependent on your...
class MyBot(commands.Bot):

    def __init__(self, *, intents: discord.Intents):
        super().__init__(
            command_prefix="supersecretjutsu",
            help_command=None,
            intents=intents,
            tree_cls=CommandErrorHandler,
        )
    async def setup_hook(self):
        coc_client = coc.Client(key_names=DevCreds.DEV_TOKEN_NAME)
        await coc_client.login(
            email=DevCreds.DEV_SITE_EMAIL, password=DevCreds.DEV_SITE_PASSWORD
        )
        self.coc_client: coc.Client = coc_client

this dont work in cog coc_client if bot dont become ready

sick birch
#

setup_hook runs before on ready

#

if you add_cog after that it will work

mild token
#

tnx

#

it worked

sick birch
#
    async def setup_hook(self):
        coc_client = coc.Client(key_names=DevCreds.DEV_TOKEN_NAME)
        await coc_client.login(
            email=DevCreds.DEV_SITE_EMAIL, password=DevCreds.DEV_SITE_PASSWORD
        )
        self.coc_client: coc.Client = coc_client

        await self.add_cog(MyCog())

MyCog can now use coc_client

mild token
#

i fixed it

sick birch
#

great

mild token
#

tnx robin

lucid ember
#

How can I check if there are any integers in a certain message sent?

fast osprey
#

Can do this pretty cleanly with regex on the message content

icy dock
#

le bhaiya omfoo

willow sable
#

i forgot to enable application.commands

#

now i have to make my commands like this

#

😭

wanton current
#

?

willow sable
wanton current
#

what does that have to do with applications.commands

willow sable
#

and i didnt when i invited it to test

#

so i spent 2 days making that system

wanton current
#

think applications.commands is granted by default

willow sable
wanton current
#

and you only need it if you want to create application commands i.e. slash commands

willow sable
#

it is required to use it

wanton current
#

then re-invite your bot with it

willow sable
#

i'd rather use it than ditch it for a new one, even if it's better

wanton current
#

okay then

drowsy thunder
#

Hello, I need to find a way to execute a piece of code when my bot joins a server.
And also leave if it doesn't have all the permissions required. How to make this function?

pure shale
#
@commands.slash_command(name="restore_verification")
    async def restore_verification(self, inter: disnake.ApplicationCommandInteraction, user: typing.Optional[disnake.Member] = None):
        await inter.response.defer(ephemeral=True)

        main_guild = inter.guild

        if user:
            target = await main_guild.fetch_member(user.id)
            print("28", target)
        else:
            target = await main_guild.fetch_member(inter.user.id)
            print("32", target)

        print(target)

        target_roles = target.roles

        print(target_roles)

        verified = False

        for role in target_roles:
            print(role)
            if role.id == config.verified_role:
                verified = True
                break

        if not verified:
            role = main_guild.get_role(config.verified_role)
            await inter.edit_original_message(f"You do not have the {role.mention} role, you can't use ``/restore_verification``!")
            return

        user_roles = self.roles.find_one({"user_id": target.id})

        for role in user_roles['obtained']:
            if role in config.verification_roles:
                await target.add_roles(main_guild.get_role(config.verification_roles[role]["Id"]))
                print(config.verification_roles[role]["Id"])

        await inter.edit_original_message("Target has been given all the roles they've been approved for!")
#

It returns None type object whenever I try to get the target's role, i have intents set up as disnake.Intents.none()

drowsy thunder
#

How to write discord badges like this?
The badges use custom emojis

drowsy thunder
#

Chat kinda dead so pls dm me the response

#

@fast osprey welp pls

fast osprey
#

Not particularly clear where you're stuck. Just how to send emojis?

drowsy thunder
fast osprey
#

It's up to you to find/choose the emojis

#

As far as badges, only a subset are exposed to bots

#

!d discord.User.public_flags

unkempt canyonBOT
slate swan
#

hi, im stuck on something on my bot, it doesn't show commands, i've always been strugglinh with it

#

here, also i want to load file from cogs folder

pure shale
#
@commands.slash_command(name="restore_verification")
    async def restore_verification(self, inter: disnake.ApplicationCommandInteraction, user: typing.Optional[disnake.Member] = None):
        await inter.response.defer(ephemeral=True)

        main_guild = inter.guild

        if user:
            target = await main_guild.fetch_member(user.id)
            print("28", target)
        else:
            target = await main_guild.fetch_member(inter.user.id)
            print("32", target)

        print(target)

        target_roles = target.roles

        print(target_roles)

        verified = False

        for role in target_roles:
            print(role)
            if role.id == config.verified_role:
                verified = True
                break

        if not verified:
            role = main_guild.get_role(config.verified_role)
            await inter.edit_original_message(f"You do not have the {role.mention} role, you can't use ``/restore_verification``!")
            return

        user_roles = self.roles.find_one({"user_id": target.id})

        for role in user_roles['obtained']:
            if role in config.verification_roles:
                await target.add_roles(main_guild.get_role(config.verification_roles[role]["Id"]))
                print(config.verification_roles[role]["Id"])

        await inter.edit_original_message("Target has been given all the roles they've been approved for!")

It returns None type object whenever I try to get the target's role, i have intents set up as disnake.Intents.none()

spring rampart
spring rampart
slate swan
#

ye dw

fast osprey
#

I strongly recommend using pkgutil rather than looping over the file system yourself

slate swan
#

okay

slate swan
spring rampart
slate swan
#

it doesn't show on my discord server

spring rampart
#

sorry bro

slate swan
#

dw

spring rampart
#

i checked ur server and its not online

slate swan
#

rn it is

spring rampart
#

ohh

#

try doing some print statements

#

well i do that so everytime i boot up the bot it tells me the cogs r working

#

but its fine

#

i hope u figure it out py_strong

fast osprey
#

What do you mean by "doesn't show"

slate swan
spring rampart
#

maybe its something to do with the commands??

slate swan
#

it loads but it's not shown

#

idk

spring rampart
#

wait it says the prefix is !

slate swan
#

ye

spring rampart
#

but did u manually make the commands into slash commands too??

#

maybe jus try the commands with !

slate swan
spring rampart
#

hmm

slate swan
#

ai code btw i need to precise it

#

but its weird tho

spring rampart
#

yehh idk

#

im not very good at python so im not too sure

#

it looks like it should work tho

slate swan
#

slash commands works without being in a folder

#

so idk

spring rampart
#

ohh wdym

slate swan
#

lemme try to out them from folder

spring rampart
#

do u mean like the slash commands work in the main code but not in cogs??

slate swan
#

ye

spring rampart
#

cuz i have that too if thats what u mean

#

OMG

#

i jus did my slash commands in the main one cuz i only have /ping and /help

slate swan
#

its so boring

#

discord whyyy

spring rampart
#

idk why discord cant jus make it easy

slate swan
#

why everything in one file like f- it

spring rampart
#

like why cant we jus say like yo @discord when the user does /ping then show the ping!!

#

BOOM

slate swan
#

ye true

spring rampart
slate swan
#

should i switch to js?

spring rampart
#

there is prolly a way to make it work but idk

spring rampart
slate swan
#

ok

#

i think it'll be better

spring rampart
#

its harder but much faster response times and more community like help and stuff

slate swan
#

ye

spring rampart
#

cuz its more common

slate swan
#

yeah

spring rampart
#

im jus too stubborn to use js

slate swan
#

i think coding discord bot is hell in python lol

spring rampart
#

yehh

slate swan
#

worst thing ever

spring rampart
#

imagine if its hell in js too

slate swan
#

lol

spring rampart
#

like imagine if coding discord bots is jus hell like however u do it

slate swan
#

ye

spring rampart
#

i might jus give up on mine icl

slate swan
#

thankfully nodejs is easier for common peopls

spring rampart
#

anyways good luck with ur bot bro

slate swan
#

thx u too!

spring rampart
slate swan
#

see ya men

spring rampart
#

adios

pure shale
fast osprey
wispy grotto
#

can anyone help me create a countdown bot that stays in a vc 24/7 and countdowns like this: 3 minutes till countdown
2 minutes til countdown
1 minute til countdown
30 seconds till countsown
10
9
8
7
6
5
4
3
2
1
Go
Please help me with this

clever sandal
#

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, "minutes till countdown")
        time.sleep(60)
        t -= 1

    print("1 minute till countdown")
    time.sleep(30)
    print("30 seconds till countdown")
    time.sleep(20)
    print("10 seconds till countdown")

    for i in range(10, 0, -1):
        print(i)
        time.sleep(1)

    print("Go!")

# Start countdown for 3 minutes
countdown(3)
fast osprey
#

It's a bit unclear what you want to actually happen. Like it sends audio at those times?

wispy grotto
fast osprey
#

Do you have the sound files you want to play?

wispy grotto
#

nah sadly not cuz im on vacation but i guess eleven or i forgot name but there you can create the sounds

#

could you hepp ne

jaunty cape
#

Give me a moment let me look in my GitHub repo

#

You have to add the β€œ/β€œ parameter

fast osprey
#

That is not required

jaunty cape
fast osprey
#

Yeah try it

jaunty cape
#

Can’t, I’m not at my computer

jaunty cape
wispy grotto
#

If anyone is bored and got literally nothing to do and would want to do something feel free to create a countdown bot for me that is talking in vc like this: 3 minutes til countdown
2 minutes till countdown
1 minute til countdown
30 seconds til cluntdoen
10
9
8
7
6
5
4
3
2
1
Go

30 sec wait time till repeat

Pls help me with this bot i need it for my server. It will pop off ong
Dont rpely if u js gon say no one gon do it pls
I need this person who can do it so pls help me when ur bored

sick birch
jaunty cape
#

if you know how to play sounds, and sleep, then you can do it

wispy grotto
#

huh

jaunty cape
#

πŸ’€

#

do you know how to play an audio file in discord voice chat

wispy grotto
#

like

#

thtough a bot?

jaunty cape
#

i'll let you answer that yourself

#

i don't wanna answer stupid questions today

wispy grotto
#

dang

#

i prob dont know

jaunty cape
#

ok can you connect a discord bot to a voice channel

#

wait what was the comand

wispy grotto
#

bru im on phone and on website and not on dc real app bc it’s glitching for me

wispy grotto
#

bro im a npcs that don know shi

fast osprey
#

They're just asking for someone to write something they want entirely for them for free, not help

jaunty cape
wispy grotto
#

oh ye good idea

#

lol

jaunty cape
#

mhm πŸ‘

wispy grotto
jaunty cape
#

but that's perfect english

#

how can you not understand

wispy grotto
#

but like

#

what u meant with it

jaunty cape
#

would you understand if i said "do you know how to do x"

wispy grotto
#

no

#

but like

#

why is it so hard to just get a bot that can clintsown like i want in a vc

#

24/7

jaunty cape
#

idk, i think it's because you don't even know how to connect a bot to a voice channel

#

how are you going to play audio if the bot isn't even in a voice channel

wispy grotto
#

is this a good code for a bot to countdown as i want?

#

import time

def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, "minutes till countdown")
time.sleep(60)
t -= 1

print("1 minute till countdown")
time.sleep(30)
print("30 seconds till countdown")
time.sleep(20)
print("10 seconds till countdown")

for i in range(10, 0, -1):
    print(i)
    time.sleep(1)

print("Go!")

Start countdown for 3 minutes
countdown(3)

wanton current
#

No

wispy grotto
#

whats wrong with it

jaunty cape
wanton current
#

if you wanna use it on a discord bot

jaunty cape
#

also, you're using time.sleep

wispy grotto
#

Could you rewrite it lol

jaunty cape
#

he was just giving you an example for a synchronous program

fast osprey
#

Let's get this out of the way. Do you have any desire to learn and experiment, or are you going to keep asking until someone writes the whole thing for you for free

wispy grotto
jaunty cape
#

it's because you're not trying hard enough

wispy grotto
#

wym

#

i had 2 books that i read and i copied and followed the book but 1 week after i still aint learn nothing besfirs like hello world

#

and i never learn what like if and else and those key words what they mean

#

i cant leadn, its like i have a learning disability

jaunty cape
#

wait. so you're trying to make a discord bot without knowing python?

wispy grotto
#

uhhh like kinda lol

#

im npcs fr i try to get everything the fast way

jaunty cape
#

you're only slowing yourself down by trying to get us to write your code

wispy grotto
jaunty cape
#

learn by writing code, not by following a book

fast osprey
#

There's no way you're going to do this without fundamental python basics. Your options here are:

  1. Put in the time to learn and experiment, there are plenty of resources but this is on you
  2. Go to a freelancing community and pay someone to build the thing you want
  3. Beg someone to make it for you for free (this isn't going to work and is just going to piss people off by you not valuing their time or skills)
jaunty cape
#

it's like in physics, memorize the entire 1000 formulas right?

#

that's wrong. memorize 3 formulas, understand what you're doing, and only use those 3 formulas for the rest of your life

wispy grotto
#

ye but

#

my brain just cant take the time that it is going to take

fast osprey
#

Then refer to option 2

jaunty cape
#

have someone study with you

wispy grotto
#

my english is trash

#

what is syntax

jaunty cape
#

your books already explained it

#

are you certain that you're trying to learn?

wispy grotto
#

yes ive tried dozens of times but i never learn so it gets boring and thten i quit

#

Me and my dad created a game just like snake

fast osprey
#

Programming is not the kind of thing that is straightforward or has immediate yields. It requires patience and resiliency.

wispy grotto
#

yes i figured

jaunty cape
wispy grotto
#

dang

#

what else then bots can i do with pytho

jaunty cape
#

practice your fundamentals

#

it's like math, you can't learn pre-calculus if you don't even know pre-algebra

#

you can't do AP physics 1 if you didn't even finish algebra 1

wispy grotto
#

yh

jaunty cape
#

in boxing, you can't do a professional fight if you can't even throw your 6 basic punches correctly

#

can you do a 540 tornado kick if you can't throw a roundhouse?

wispy grotto
#

ye ur righy, im jusg looking for stuff the easy and wuick yway

jaunty cape
#

trying to do things from the top is the quick and really hard way

fast osprey
#

There is no easy and quick way

jaunty cape
#

you have to start from the bottom

wispy grotto
#

donyou have any tips like how i should start learning

#

and how to make it fun

jaunty cape
#

idk i kinda just solved problems after learning what everything does and how it works

wispy grotto
#

what kknd of problems

#

and did yoi create any games?

jaunty cape
#

no i solved problems such as - 3 5 = -2

#

i believe this is called "prefix notation evaluation"

#

Prefix notation is a mathematical notation. It is a way to write down equations and other mathematical formulae. Prefix notation is also known as Polish notation. The notation was invented by Jan Łukasiewicz in 1920. He wanted to simplify writing logic equations.
When prefix notation is used, no grouping elements (like parenthesis) are needed.
W...

wispy grotto
jaunty cape
#

- 3 5 is the same as 3 minus 5

wispy grotto
#

-2?

#

oh

#

but then thats ez

jaunty cape
#

nah, some CS graduates weren't able to solve it when my teacher interviewed them

#

it is an easy problem though

wispy grotto
#

now that u said how to do

#

it was easy, can u say another one similar to that ine

#

wait wait u solved that problem coding?

jaunty cape
#

yes.

sick birch
#

you should find a project that is both within your skill level and has use to you

#

this is the optimal way of learning

#

this is what i usually tell people when they ask others to suggest a project for them, you know yourself better than we do and you can pick a project out for yourself based on your interests far better than we can

wispy grotto
#

ye well my skill is at 0 lol

sick birch
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

jaunty cape
#

serious? this server had a resources page the whole time?

sick birch
#

A Byte of Python and Automate the Boring Stuff come highly recommended

wispy grotto
#

if i dedicate myself rlly much to learn would it take years to learn python and how to create a bot like the one i want

sick birch
#

it will not take years

#

but we cannot tell you how long it takes because it varies wildly from person to person

jaunty cape
#

i personally took 3 months

wispy grotto
#

dang

#

how much daily did you practice

jaunty cape
#

when i started i didn't even have a computer, so i took classes once a week

wispy grotto
#

oh

#

dang

jaunty cape
#

yeah the teacher had these really cool machines with linux mint installed on them

wispy grotto
#

lol

graceful raven
#

Good Evening everyone! I have come up with a python file to do some status checking on certain game servers. My question is, how can I transform this so it can go into my bot? Or would a webhook be better? I'm not really sure because this is something that checks on an interval basis on isn't through a command. Does anyone have suggestions or recommendations?

https://paste.mozilla.org/E4J4D9qp/raw

torn solar
#

for some reason im rate limited on my bot

#

from discord and it only probably gets a few request every couple hours

sick birch
drowsy thunder
#

Chat dead fr

vocal laurel
vague sonnet
#

I'm making a bot on a host, I get an error and I think it's something with the token, can I send you the code of my bot and you can check what's wrong? My bot doesn't turn on because of that error and I don't know what's wrong.

fast osprey
#

What is the error?

drowsy thunder
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

drowsy thunder
#

@fast osprey any idea how to open a modal from a button?

slate swan
#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
drowsy thunder
zinc gust
#

wsg so i did a dmall command and like it says that people dm are closed while its not (it was working fine like 2 hours ago)

fast osprey
#

What exactly is dmall

wanton current
#

small

zinc gust
#

with a command

fast osprey
#

Did all of the user's consent and ask the bot to get dm'd?

zinc gust
#

no

#

but like if they got their dm on it means they consent receiving dms from people

fast osprey
#

This is against developer policy then. You should use pings within the server

zinc gust
#

my question wasnt if it was against tos

fast osprey
#

You should refer to the server rules first, then

zinc gust
#

still

#

isnt my question

fast osprey
#

What do the rules say?

zinc gust
#

havent read it tbh

fast osprey
#

Pretty bold thing to admit

#

Let me help you out though:

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

If what you're asking for help with violates discord's tos (it does), that is against the server rules to ask for help with it or for us to provide help with it. Lucky for you, there is a very straightforward solution that accomplishes the core goal that does not violate TOS

sick birch
# zinc gust havent read it tbh

you agreed to the rules by joining and chatting in the server. it is unwise to agree to something without knowing what it is that you are agreeing you.

fast osprey
#

Is there a confusion about what "rules" means? what

velvet compass
# zinc gust wym

#rules has a list of rules for the server, and this project would run into rule 5. We would not want to assist with a mass DM spam bot

#

The preferred way for a bot to interact with lots of people in a server would be a ping in channel

slate forum
# zinc gust wym

In simple terms, asking for help that goes against Discord's rules (Terms of Service) is not allowed. This server follows those rules, so we can’t assist you with anything that would break Discord's TOS.

slate swan
wispy grotto
#

yo guys my friend is making a discord bot i think through discord.py but his pc is x84 and not 32 or 64 anyone who cpuld like put code in and make bot but like not script it and stuff meaning that my friend will send the code and stuff and you just put it in

fast osprey
slate swan
sick birch
#

what even is x84

#

ima assume you meant x86

#

its an instruction set for 32 bit processors so not sure what that has to do with a discord bot?

mortal dust
#

hey, anyone able to help with a discord python bot where I can use the commands globally?

fast osprey
#

What's the problem/question?

mortal dust
#

but cannot figure it out haha

fast osprey
#

What have you tried!

mortal dust
#

import discord
from discord.ext import commands
from discord import app_commands

TOKEN = 'tokens' # Replace with your bot token

intents = discord.Intents.default()
intents.message_content = True # Enable message content intent if necessary
bot = commands.Bot(command_prefix='/', intents=intents)

@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
try:
# Sync global commands
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(f"Failed to sync commands: {e}")

@bot.tree.command(name="test", description="Vouch")
async def test(interaction: discord.Interaction):
await interaction.response.send_message("Vouch")

bot.run(TOKEN)

fast osprey
#

So firstly, you need to remove your sync from on_ready

#

Or you're going to lock yourself out of development entirely

#

Secondly, you don't need user installs to run commands in dms. That works just fine for regular global commands, assuming you share a guild with the bot

mortal dust
#

you're awesome for responding

#

but how do I get it working uglyassquestion , could you modify for me?

fast osprey
#

nwnw! If you do want user installs specifically, you'll need to add the context for it. But you probably don't need it in this case

#

I don't write code for people

mortal dust
#

what am I missing for this to work properly then?

#

because the fixes you mentioned aren't what should be preventing me from being able to use it in dms

#

am I missing something in dev portal?

fast osprey
mortal dust
fast osprey
#

This will allow you to actually fix the problem

#

If you do not do this, you will not be able to make any changes in the very immediate term

mortal dust
#

so after removing sync, what's the next action I should take?

fast osprey
#

Are you in a shared guild with the bot?

mortal dust
#

yes

fast osprey
#

Have you refreshed your client since syncing commands?

mortal dust
#

yes

fast osprey
#

Is the command in the guild's integrations tab?

mortal dust
#

My bad internet went out, I’m tryna use the bot in DMs

#

Not in a guild

#

It works in guilds

slate swan
#

Does anyone know how to make a stock bot for my discord

#

i have a website called sellauth

#

The api key is different i think, i tried using chatgtb but hes dumb

normal lava
#

hi

normal lava
#

i made a economy bot like owo now what should i do next ..

limber jolt
#

Error fetching bot guilds: 401: Unauthorized

fast osprey
#

What is the full error, including traceback?

limber jolt
#

Also ping on reply

fast osprey
#

But what is the error

#

And what is the code

limber jolt
limber jolt
# fast osprey But what is the error
 * Serving Flask app 'server'
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 235-583-904
127.0.0.1 - - [01/Aug/2024 08:32:04] "GET /thank?code=J6XtUhVR9PL4Sf2OgSNys5jXcQhY31&guild_id=1244010476569100318&permissions=8 HTTP/1.1" 404 -  
127.0.0.1 - - [01/Aug/2024 08:32:23] "GET /thank?code=J6XtUhVR9PL4Sf2OgSNys5jXcQhY31&guild_id=1244010476569100318&permissions=8 HTTP/1.1" 404 -  
127.0.0.1 - - [01/Aug/2024 08:32:34] "GET / HTTP/1.1" 200 -
Error fetching bot guilds: 401: Unauthorized
127.0.0.1 - - [01/Aug/2024 08:32:38] "GET /dashboard HTTP/1.1" 200 -```
fast osprey
#

Your first step is to get the full error, including the traceback

limber jolt
fast osprey
#

Whatever you have now is just swallowing the traceback

#

It is not

limber jolt
fast osprey
#

Because you're throwing it away

#

"Error fetching guilds" is not something python, discord, or flask would put out. That is you

#

This typically comes from people try/excepting blanket Exceptions, printing the exception itself and throwing away all of the useful bits. In general you really should not be writing error handling like this

next oasis
low robin
#

Can anybody explain me how to create a custom status for my discord bot? Without the Playing, Watchting etc. Just a text

vestal crest
#

im following a tutorial at the moment and it said to go to terminal and type pip install discord or pip install discord.py yet it doesnt recognize pip as anything

low robin
vestal crest
#

yes i have

exotic hazel
#

try that

vestal crest
#

oooo tysmmm

opal vortex
#

or better than installing

#

git clone https://github.com/python/cpython.git --branch main
./configure
make install

wanton current
#

yeah because it's easier running 1000000 tests than pressing a download button

wanton current
#

outdated

graceful raven
#

This is the activity without "Playing", "Watching" or "Streaming"

low robin
#

Thanks

graceful raven
gritty inlet
#

Any idea why this code:

async def get_upvote_count():
    """
    Function to get the upvote count of the bot from Top.gg.
    """
    url = f"https://top.gg/api/bots/{BOT_ID}"
    headers = {"Authorization": TOPGG_TOKEN}

    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers)
            response.raise_for_status()
            bot_data = response.json()
            monthly_points = bot_data.get('monthlyPoints', 0)
            total_points = bot_data.get('points', 0)
            return monthly_points, total_points
        except httpx.HTTPError as e:
            print(f"HTTP error occurred: {e}")
        except Exception as e:
            print(f"An error occurred: {e}")

    return 0,0

@bot.tree.command(name="vote", description="Upvote the bot on Top.gg!")
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def vote(interaction: discord.Interaction):
    monthly_votes = await get_upvote_count()
    total_votes = await get_upvote_count()
    embed = discord.Embed(
        title="Vote:",
        description="Go upvote PlaceHolder on **Top.gg**!\nHelp us grow the bot!",
        color=discord.Color.blurple(),
    )
    embed.set_thumbnail(url='https://cdn.top.gg/icons/7b707bf868adef7730776f171a2dc709.jpeg')
    embed.add_field(name="Monthly votes:", value=f"`{monthly_votes}`", inline=True)
    embed.add_field(name="Total votes:", value=f"`{total_votes}`", inline=True)

    view = discord.ui.View()
    view.add_item(discord.ui.Button(label="Go vote!", url={URL}, emoji=':placeholder:', style=discord.ButtonStyle.link))
    view.add_item(discord.ui.Button(label="Bot page", url={URL}, emoji=':topgg:', style=discord.ButtonStyle.link))

    await interaction.response.send_message(embed=embed, view=view)```


Gives a 404 error? ("unknown interaction")
It worked a few hours ago, but Idk why now it doesn't.
#

πŸ€”

fast osprey
#

You're taking more than 3 seconds to respond

gritty inlet
#

Yeahhhhh i got it solved now

#

Lol, network issue

slate swan
#

my errol

#

pls help me

wanton current
#

Did you read the warnings

slate swan
fast osprey
#

Both of those are not good places to run bots

willow sable
#

why are discord.py buttons supposed to be like this

async def btn(self, interaction: discord.Interaction, button: discord.ui.Button):

instead of

async def btn(self, button: discord.ui.Button, interaction: discord.Interaction):
mild token
#

Context menu can have how many parameters?

willow sable
#

commands or..

mild token
#

On a message like a report command with 2-3 more parameters

#

Is it possible to give multiple parameters to context menu?

#

Like we do for slash?

willow sable
#

like

@client.command()
async def cmd(ctx, arg):

?

#

or am i stupid

mild token
willow sable
#

there is a ctx argument in commands

#

so i dont really know what you're referring to

mild token
#

I am talking about context menu

willow sable
#

hang on let me google

#

oh

mild token
#

!d discord.app_commands.context_menu @willow sable

unkempt canyonBOT
#

@discord.app_commands.context_menu(*, name=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command context menu from a regular function.

This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.

Examples...
willow sable
#

ok i got it

crude remnant
#

uh, someone help, I am new to discord python stuff and when my bot is on and I execute a slash command code the previous slash command won't show up

#

plz help a brutha out πŸ™

fast osprey
#

What do you mean by "won't show up"?

slate swan
#

hi

#

someone can help me making an discord bot what getting pysilon samples form Triage and ungrabbs the discord bot token form it

#

and sends it to the discord server

fast osprey
#

What exactly does "ungrabbs" mean and what are you doing with a token 🀨

slate swan
#

like remove the bot form the server

#

or dm the victims

#

like this

fast osprey
#

I have no idea what a "grabber" is

slate swan
#

but auto mated

#

a grabber is that grabbs paswords

fast osprey
slate swan
#

but form pyisntaler files

#

gets the bot token

fast osprey
#

Who is getting what bot token, and how

slate swan
#

like a bot token the login of the discordbot

fast osprey
#

That doesn't answer my question. I know what a token is

slate swan
#

you know pysilon

fast osprey
#

What is the exact scenario playing out here, it's entirely unclear what you are trying to do

slate swan
#

get the samples from triage and gets the token form the pyinstaller file

fast osprey
#

What are you trying to do

slate swan
#

and sends to a discord server

fast osprey
#

I'm going to get out ahead of this conversation and inform you that distribution of bot credentials (including tokens) is strictly prohibited by the TOS regardless of how you're getting them unless you are qualified as a service provider of that particular bot

slate swan
#

but those are cyber criminals

fast osprey
#

Okay...? So again, what are you doing?

slate swan
#

im not doing it

#

but i trying

#

look up pysilon

fast osprey
#

That doesn't tell me what you're trying to accomplish, you're just throwing buzz words around

#

Without using any specific library or framework, what is the problem you're trying to solve? Someone else has some bot token, what are you trying to do with your code?

graceful raven
# fast osprey Okay...? So again, what are *you* doing?

Solstice, what he is referring to is "grabbing". This is referred to as stealing tokens that allow unauthorized users to steal tokens or session cookies to login. This effectively bypasses MFA/2FA. This is a very big thing in Discord actually especially in communities where rare Discord account names may exist, rare badges, etc. Or just trying to mess with someone.

fast osprey
#

Right, I know what this means. What is very unclear is what they specifically are trying to do, materially

graceful raven
#

I will agree it's severely unclear what he's trying to achieve but it sounds like he's trying to defeat this malware (PySilon) in an automated fashion by taking malware samples and doing something with them. But I have 0 understanding on how he will do that with a discord bot

fast osprey
graceful raven
#

Yeah, no that is of concern as well. Tokens shouldn't be sent in a server. Again, I agree that it's a little odd.

stark ingot
#

I believe that sending a bot token to a discord server automatically invalidates it.

wanton current
#

no

glad cradle
stark ingot
# wanton current no

From what I can tell you are right and my statment was wrong. IDK why discord does not do it as they warn you not to send tokens so they know a token has been sent.

fast osprey
#

May be legitimate cases shrug . Dev team on a private server or something

slate swan
#

is it possible to change the bots banner via command?

wanton current
#

?rtfm commands.Bot.user.edit

#

damn

#

!d discord.ClientUser.edit

unkempt canyonBOT
#

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

Edits the current profile of the client.

Note

To upload an avatar, a [bytes\-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes\-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) is given through the use of `fp.read()`.

Changed in version 2\.0: The edit is no longer in\-place, instead the newly edited client user is returned.

Changed in version 2\.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
slate swan
#

how to get datetime like this? like the gray thing around it

fast osprey
#

!d discord.utils.format_dt

unkempt canyonBOT
#

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

This allows for a locale\-independent way of presenting data using Discord specific Markdown...
tight obsidian
#

Hello @alpine summit, this channel is unrelated to hip-hop unfortunately.

snow coral
spring ferry
graceful raven
spring ferry
#

Code working but when !MIB

#

It's doesn't reply me also bot shows offline

#

@graceful raven

jade jolt
merry cliff
jade jolt
#

what

timber dragon
spring ferry
#

Bot is not replying

timber dragon
#

The issue there is the way you import the datetime module

you:

from datetime import datetime
datetime.utcnow(), datetime.timezone.utc

fix:

from datetime import datetime, timezone
..., timezone # not datetime.timezone

recommended fix:

import datetime
datetime.datetime.utcnow(), datetime.timezone.utc

slate swan
#

!d datetime.timezone

unkempt canyonBOT
#

class datetime.timezone(offset, name=None)```
The *offset* argument must be specified as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object representing the difference between the local time and UTC. It must be strictly between `-timedelta(hours=24)` and `timedelta(hours=24)`, otherwise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised.

The *name* argument is optional. If specified it must be a string that will be used as the value returned by the [`datetime.tzname()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzname) method.

Added in version 3\.2\.

Changed in version 3\.7: The UTC offset is not restricted to a whole number of minutes.
spring ferry
#

Huh where ? Can I share my code

slate swan
#

Yes

timber dragon
#

Sure

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

spring ferry
#

Ok

#

@slate swan @timber dragon

timber dragon
#
from datetime import datetime, timedelta
spring ferry
#

At top ?

slate swan
#

timezone is submodule of datetime

#

Just add it to imports

timber dragon
#

And line 42 is the error

spring ferry
#

Actually I don't know python I made this script using gpt and my knowledge can you tell me

timber dragon
#

I would recommend replacing the import with just import datetime

#

Bruh

spring ferry
#

Ok

#

Right?

timber dragon