#discord-bots

1 messages · Page 373 of 1

woeful karma
#

thank you!

upbeat otter
slate swan
slate swan
#

is that a yes? im asking if thats okay

upbeat otter
#

you can

stoic tusk
#

Anyone hosting their discord bots on render.com? need some help

sinful galleon
#

Heya CatBongoWave0 I'm using Python and Nextcord to make a discord bot and I'm trying to create a button that adds a specific role (verification role). Does anyone know how to code a button like that? It would be handy if that role couldn't be removed too so that members don't verify and then unverify.

#

I'm a noob so any help would be appreciated Sob0

lyric sphinx
#

although discord itself has a thing like this for community servers now, you could use that instead of reinventing it, but eh, whatever

quick gust
#

I think they want a persistent button

sinful galleon
sinful galleon
sinful galleon
quick gust
#

you can use this example

#

and have the logic to check if a user has the "verified" role

sinful galleon
#

I appreciate the help <3

karmic elk
#

hey guys does the voicechannel class not have a .play function anymore?

#

i dont see it in the docs

wanton current
#

never had one

#

afaik

#

do you mean voiceclient

karmic elk
#

how do we get bots to play music in the vc then?

#

i got it to connect and i have the file

karmic elk
#

i might sound dumb but how do i create an instance of VoiceClient to use the .play() thing

#

i have only vc rn

wanton current
#

guild.voice_client should work

karmic elk
#

will i not need to specify the vc id or anything?
so just guild.voice_client.play(......) ?

wanton current
#

i mean

#

the bot can only be in one vc at a time

#

so the latter should work

karmic elk
#

k ill try

#

its not playing anything neither is it giving an error idk whatds wrong
self.vc.play(discord.FFmpegPCMAudio(song, **self.ffmpeg_options))
self.vc is the voiceclient
song is the url
ffmpeg_options = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn -filter:a "volume=0.25"'}
do uk whats wrong?
error

File "/home/runner/xylan/src/music.py", line 76, in play_music
    self.vc.play(discord.FFmpegPCMAudio(song,  **self.ffmpeg_options), after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next(), self.bot.loop))
  File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/voice_client.py", line 614, in play
    self.encoder = opus.Encoder()
  File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/opus.py", line 323, in __init__
    _OpusStruct.get_opus_version()
  File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/opus.py", line 316, in get_opus_version
    raise OpusNotLoaded()
discord.opus.OpusNotLoaded
fast osprey
vapid parcel
#

can you do select menus in modals?

#

or are modals all text?

wanton current
#

all text currently

vapid parcel
#

L discord

#

Well then im here for an IDEA. How can I get a country, but then need to import a flag but an emoji basically, just skip to 1:23 in the video

#

Skip to 1:23 in the video, how can I improve the country feature?

wanton current
vapid parcel
#

Can you do autocompletes in modals?

wanton current
#

no

lunar vine
#

ii cant see any

tight obsidian
#

@elder vale what about SD?

wanton current
#

probably typo of "sad"

pale zenith
#

does sd have some meaning that I don't know?

#

đŸ€”

blazing beacon
vapid parcel
#

Well this is how I decided to do country I guess lol

#

wish I couldve done it in a modal

#

but modals are limited on "support"

slim bloom
#

code : py @bot.command(name='helpp', description='asd') @commands.cooldown(1, 15, commands.BucketType.user) async def helpp(ctx): embed = discord.Embed(title=f'Lista de comandos ({len(bot.commands)})', color=0xEBE8EC) for command in bot.commands: embed.add_field(name=f'{bot.command_prefix}{command.name}', value=command.description, inline=False) await ctx.send(embed=embed) error: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.fields: Must be 25 or fewer in length. how fix?

sick birch
slim bloom
sick birch
#

embeds can have a max of 25 fields

slim bloom
#

😔

upbeat otter
karmic elk
#

yea

upbeat otter
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
karmic elk
#

its against toc?

upbeat otter
#

read the 3rd point

karmic elk
#

what to do the bots use then

upbeat otter
#

major music bots have gone down, it's just the small bots

#

that use youtube

karmic elk
#

oh kk

pallid crater
#

its annoying they don't like you downloading videos ig its about ads and stuff you don't get served ads if you have it downloaded

karmic elk
#
raise OpusNotLoaded()
discord.opus.OpusNotLoaded

what does this error even mean tho?

upbeat otter
pallid crater
#

if I owned something "like youtube" it wouldn't be a money grabbing corporation but rather a video sharing platform based around comunity that anyone is welcome to save content they enjoyed on

#

so. actually you couldn't be more wrong

upbeat otter
#

how're you gonna pay the content creators then
And it's easy to say that, but practically that's not possible

I mean who would miss their chance to scale their application to a billion dollar company

pallid crater
#

also. there are already bots downloading youtubes content. the TOS does little about it

#

youtube is profitable. therefore. it would be proftiable if that weren't in the TOS

upbeat otter
#

don't know, if it's against the TOS, I would rather support it than illegally use it even though there are no consequences

pallid crater
#

đŸ€Ł why. its an evil corporations attempt to hoard wealth

#

lol

upbeat otter
#

aight its pointless to argue

pallid crater
#

sorry. not arguing. you're entitled to your opnion I am just curious about the movite. it sounds strange to me is why I was laughing. you're entitled to your opinion

#

I'm not trying to ridicule you that might have seemed rude. its just to me kind of yano "what lol" cos i don't get it but thats fine

#

🙂

#

personally I always advocate for trying to do whats RIGHT. and that be the be all and endall

#

but we'll leave this there

fierce cloak
#

How long until all music bots are banned?

upbeat otter
upbeat otter
drifting arrow
#

How do I make my looped task not do an initial run on bot startup?

#
@tasks.loop(minutes=3)
async def squadlogs_updater(self):
    await asyncio.sleep(5)
    print("------------------------")
```When I turn my bot on, and do `self.squadlogs_updater.start()` this will run after 5 seconds instead of 3 minutes
drifting arrow
#

No.

waxen bolt
#

oh wait

drifting arrow
#

You misunderstand. When I load the bot, the task runs when the bot loads so I had to put that sleep in so the bot can load properly.

I dont want the task to run right away when the task is started, I want it to wait 3 minutes

scarlet tiger
shrewd apex
#

like bot.uptime

#

another way is u use something like asyncio.create_task and add a sleep of mins before calling squadlogs_updater.start

turbid shard
#

hi everyone

#

i need to find out how to make a command user installable and guild installable

drifting arrow
fast osprey
#

You could just put whatever in the before_loop btw

drifting arrow
#

eh this works and im happy

fast osprey
#

Not a very good attitude to have in software engineering but you do you

wanton current
slate swan
#

I dont really know how to make my embed look like the first one, how?

slate swan
#

Will somebody help me gahdamn

slate swan
#

Just copy the first example

#

Change to suit your needs

#

Remove items you dont need

#

And done

upbeat otter
#

uhhmmm, guys how do I receive multiple Role objects in a single argument

#

something like

roles: Role #need to have multiple roles
upbeat otter
wanton current
#

yeah there's Greedy too

#

depends on if you wanna raise an error or not if it can't parse an argument

upbeat otter
#

aight, thanks

wanton current
#

nw

nimble jetty
#

can you guys help with discordpy-self?

wanton current
#

no

nimble jetty
#

why

wanton current
nimble jetty
#

it's for my own server and discord.py already supports self bots i dont see the problem

fast osprey
#

No, it doesn't

wanton current
nimble jetty
#

i'm trying to make it so i automatically respond when someone says hi

wanton current
#

and it's against ToS

nimble jetty
fast osprey
#

Please refer to the rules here

ocean spindle
wanton current
#

probably

ocean spindle
wanton current
#

why

ocean spindle
elder tinsel
#

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

turbid shard
#

hi

#

anyone wanna help me

wanton current
#

hi

turbid shard
#

i need help

#

like really bad 💔

wanton current
#

don't ask to ask

turbid shard
#

like if i do user install guild install wont work

#

idk how to fix it, this sucks sobbing

turbid shard
#

nvm

#

@wanton current are u available perchance

sturdy egret
#

Hey guys im trying to send a view to a webhook, using view=ButtonSendCode(). Im doing await webhook.send(embed=embed, view=ButtonSendCode()),

#

however it keeps erroring any help?

#
ValueError: Webhook views require an associated state with the webhook
#

Thats the error code ^

golden portal
high narwhal
#

hi ^^' how can i make the bot to have localized languages?

golden portal
unkempt canyonBOT
#

class discord.app_commands.Translator```
A class that handles translations for commands, parameters, and choices.

Translations are done lazily in order to allow for async enabled translations as well as supporting a wide array of translation systems such as [`gettext`](https://docs.python.org/3/library/gettext.html#module-gettext) and [Project Fluent](https://projectfluent.org).

In order for a translator to be used, it must be set using the [`CommandTree.set_translator()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.set_translator) method. The translation flow for a string is as follows:
high narwhal
hollow kraken
#
 if reaction.emoji == '1\uFE0F\u20E3':

                with open(FILE,"w") as fp:

                    json.dump(DEFAULT_DATA,fp)
                print(icon)
                print(icon is None)
                if icon is None:
                    print("running")
                    await set_icon(channel,ctx)
                    
                
                await add_teams(ctx,channel)
                await set_cap(ctx,channel)
                await preseason(ctx)

hey in this code, all the functions past set icon are not waiting for set icon to finish, anyone know the reason why?

drifting arrow
echo bridge
#

i wanted to use an api that was coded in javascript can i use it in python

#

?

rugged shadow
#

you can use them from any language

echo bridge
#

thanks

simple prawn
#

hi

@bot.command()
async def send(ctx, user: int = None, *, message):
    if user is None:
        await ctx.send("Tu dois spécifier l'ID de l'utilisateur.")
        return
    
    try:
        target_user = await bot.fetch_user(user)
    except discord.NotFound:
        await ctx.send("Utilisateur non trouvé.")
        return
    except discord.HTTPException:
        await ctx.send("Erreur lors de la récupération de l'utilisateur.")
        return
    
    try:
        await target_user.send(message)
        await ctx.send(f"Message envoyé à {target_user.name}.")
    except discord.Forbidden:
        await ctx.send(f"Je n'ai pas la permission d'envoyer des messages Ă  {target_user.name}.")
    
@bot.event
async def on_message(message):
    print(message.author.id)
    print(bot.user.id)
    if message.author.id == bot.user.id:
        return
    if isinstance(message.channel, discord.DMChannel):
        embed = discord.Embed(
            title="Nouveau message reçu",
            description=f"Contenu du message : {message.content}",
            color=0x00ff00)
        
        channel = bot.get_channel(1251915975746650244)
        if channel:
            await channel.send(embed=embed)
        else:
            print(f"Le salon avec l'ID {1251915975746650244} n'a pas été trouvé.")
    else:
        print(message.channel.name)
    await bot.process_commands(message)
#

@slate swan can u help me pls

slate swan
#

I think i missed the part when you actually Ask your question

simple prawn
#

@slate swan

slate swan
#

You never said what's the issue nor asked any questions

simple prawn
#

but i don't want it to send that message

slate swan
#

Bot likely running twice

dense flame
copper flume
#

i need both the channel id and object

dense flame
#

are you sure

copper flume
#

it is best to store channel object in dict key or the channel id

smth[channel.id] = {"channel": discord.TextChannel}```
OR
```py
smth[channel] = {"author": commands.Author}```
slate swan
#

id

#

IDs are there for a reason

hollow kraken
pallid crater
#

sorry to barge in on a tangent but you guys seen the changes to premium bots? I don't make them. I don't use them. still sad and disappointing

stray flicker
#

how do i make it like:

i type the command !numbers
the bot reacts with number emojis (1ïžâƒŁ, 2ïžâƒŁ, 3ïžâƒŁ, ...) from 1 to 9
i react on one of them
it returns the number (1, 2, 3, ...) i reacted on

pallid crater
#

use waitfor

#
await ctx.send(reaction[0]})

is how you will send it

simple prawn
olive basin
#

I need to make a bot for slack

outer horizon
#

Hi I am new here

olive basin
#

I want to send the responses that have errors in them in the django server to the slack server so the team can work on them

upbeat otter
#

why do you wanna overcomplicate things

#

Or just make a UI in your django server to view and work on the errors

mental eagle
#

i'll shoot my shot here đŸ€­

So i have started to code my own bot, i have absolutely no knowledge on how to, but a basic understanding

im using python and visual studio code, i have wrote the first part of the bot, ran the file and got no syntax erros, but when i try to run the command from the terminal in VSC it doesnt work and this is the error i recieve

C:\Users\gavin> python WNW1.py
Traceback (most recent call last):
File "C:\Users\gavin\WNW1.py", line 4, in <module>
client = commands.Bot (command_prefix= '/')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

wanton current
#

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

olive basin
upbeat otter
#

hmm I see

fast osprey
#

Disclaimer that this guide is not endorsed or reviewed by the library maintainers. The API docs and examples in the relevant library you're using will be definitive

mental eagle
wanton current
mental eagle
wanton current
#

I did, read the thing the bot sent, you're missing the intents=... from your code.

mental eagle
wanton current
#

That video is outdated then

mental eagle
wanton current
#

sure

mental eagle
elfin marten
#

Hey! Am I missing something or is there just no documentation for slash commands in discord.py?

#

I found a 3 year old post on stackoverflow and thats it

slate swan
#

The last one real

elfin marten
#

I don't see in documentation the last thing I need... any idea how to increase time before a slash command will fail and respond with command timeout?

hushed galleon
#

interaction.response.defer() is what you'd use for that

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
hushed galleon
#

note that deferring is itself a response so your subsequent message will need to be sent as a followup, i.e. interaction.followup.send(...)

limber jolt
hybrid fjord
#

im tryna pip install yfinance but it doesnt work, any clues? maybe its an issue with the environment
it works in other files perfectly, its just this folder where it doesnt seem to detect the pip

glad cradle
hybrid fjord
#

elaborate

glad cradle
#

tho you probably need to update Windows powershell polices before that

hybrid fjord
#

oh

#

ok let me try that

#

it worked, thanks very much

glad cradle
#

np

glad cradle
hybrid fjord
#

ah ok

mental eagle
#

is anyone able to help with errors on my bot? wrote on python using visual studio code

i connected it to nitrado and ran it, it went online but wasn't sending logs as i didnt import requests

wince i imported requests and set my command to get the logs, it now won't recognise my nitrado api đŸ€”

fast osprey
#

Code and errors would be a good start.

If you're using an asyncio framework like discord.py (or any of its forks), you really should not be using requests at all

reef gazelle
#

I was initially using Disnake last time I made a bot so feel like I might go back to it as felt better the way it handled slash commands

hushed galleon
slate swan
crystal flint
hexed mesa
#

who wants to make a discord bot using openai?

rugged shadow
#

oh hell nah

#

you're gonna go broke paying for tokens

merry cliff
#

XD

#

I just use gpt4free

#

a quick peruse of the docs makes me think this is not available but you could do something like py @bot.command(name="trigger") async def get_member_messages(ctx, member: discord.Member): await ctx.defer(thinking=True) total = 0 for channel in ctx.guild.channels: if isinstance(channel, discord.TextChannel): history = channel.history(limit=None) async for message in history: if message.author.id == member.id: total += 1 await ctx.send(f"{member.mention} has {total} messages sent")

#

it does take a long time

upbeat otter
#

and a lot of requests

merry cliff
#

It’s definitely possible though bc !user can do it

#

!user

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

merry cliff
#

Ok I looked at the source ode

#

It basically adds to a counter every time you send a message

#

There’s not a way to get it as a value unfortunately

sick birch
#

I haven't had time to play around with the globally installable apps yet - but can they DM the user that it's installed for? I've got some project ideas with these but they require being able to DM the user for which it's installed under. Tried looking at the docs but it seems to focus mostly on the ablity to be invoked from anywhere (and their interaction responses)

blazing beacon
#

i had a skill issue

@commands.Cog.listener('on_message')
    async def ai_listen(self, message : Message):
        
        ctx = await self.bot.get_context(message)
        user_id = f"{ctx.guild.id}-{ctx.author.id}"
        
        if message.author.id == self.bot.user.id or not self.bot.user.mentioned_in(message):
            return
        
        if user_id not in context_window:
            context_window[user_id] = []

        context_window[user_id].append(f"{message.author.name}: {message.content}")

        if len(context_window[user_id]) > config["MAX_CONTEXT_WINDOW"]:
            context_window.pop(0)
        
        await ctx.channel.typing()

        attachments: Attachment = message.attachments

        remembered_memories = Memories().compare_memories(user_id, ctx.message.content)
        if remembered_memories["is_similar"]:
            prompt = read_prompt(ctx.message, remembered_memories['similar_phrase'])
        else:
            prompt = read_prompt(ctx.message)

        if attachments and attachments.filename.endswith(".png", ".jpg", ".webp"):
            save_name = f"{message.guild.id}-{message.id}"
            attachments.save(save_name)
            image = Image.open(save_name)
            await ctx.reply(BotModel.generate_content(prompt, user_id, image), mention_author=False) # download attachments[0] in `attachments` 
        else:
            await ctx.reply(BotModel.generate_content(prompt, user_id), mention_author=False) 

^^ - Relevant code

Traceback (most recent call last):
  File "c:\Python312\Lib\site-packages\discord\client.py", line 444, in _run_event
    await coro(*args, **kwargs)
  File "d:\Python\Gemini-AI-Bot\v0.5a\cogs\ai_beta.py", line 49, in ai_listen
    attachments.save(save_name)
    ^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'save'
fast osprey
#

You may wish to review the updated developer TOS going live on July 8th

rugged shadow
fast osprey
#

Yes

#
  1. Do not use message content obtained through the APIs to train machine learning or AI models (including large language models) unless express permission is granted by Discord.
rugged shadow
#

i cant read their code

#

but it doesnt look like training AI

blazing beacon
#

i am also aware of the updated TOS

blazing beacon
fast osprey
#

Right, because you know what Gemini is doing under the hood with what you send it stuff, and you're also adhering to the requirements of sending user data to third parties I bet

blazing beacon
#

or ill just end this project, i literally cant face anymore roadblocks, i've been working on this shit for 12 days straight and every time i make progress i lose it

#

im just gonna put it on a shelf until i can even feel sane

blazing beacon
#

disregard my previous messages, i was not in a state of mental clarity when writing them. i do apologize and thank you for your time

fast osprey
#

You're fine, it's just important to understand the responsibilities when you're passing user data along to third parties. The line of "training" or not is murky when you don't actually control the model

blazing beacon
#

i wish i could use Gemma 2b and just cut it offline lol, i really do. but my computer is too slow for it to even generate the response in a meaningful amount of time

#

my entire computer turns into a slideshow the second i run the model and it loads the model checkpoint, and then it takes an additional 20 minutes to produce a response along the lines of

"I’m not sure what you mean by “write me a poem about Machine Learning.”"

however i digress, and must accept this as a skill issue.

fast osprey
#

Tbh haven't dug into what the guarantees are on how Gemini uses api inputs, but you're effectively sticking your neck out for them. Plus that's on top of the requirements for any sharing of user data with third parties (getting and recording the user's explicit instruction to do so)

blazing beacon
drifting arrow
#

idk what we're discussing, but it doesnt look like code.

#

So can someone share code so I can be reminded what it looks like

hearty basalt
#

rn while using the @commands.has_any_role() i'm passing thru a list of role names (it works). if i use role IDs will it work the same or do i need to add extra steps (getting the roles from the IDs)?

hearty basalt
mental eagle
#

is anyone around able to help, currently on day 2 of an issue with my bot

coding on VSC, everything was working as it should until i asked it read logs from nitrado, now i get this

#

line 26, in <module>
client = commands.Bot (command_prefix="/"),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

hearty basalt
mental eagle
hearty basalt
#

did you save it before running again?

#

omg i just noticed you don't have intents specified lmao mb

#

after your prefix, specify intents with intents=

#

i mean i have my intents set to
intents = discord.Intents.all(), but you can specify them separately

#
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=commands.when_mentioned_or('.'), help_command=None, intents=intents)

this is from my code :p

mental eagle
#

i was just about to ask, do i put in just intents=intents or is there anything else should add

hearty basalt
#

here's the docs for intents if you want to go more indepth

mental eagle
#

thank you bud ✌

hearty basalt
#

<3

mental eagle
#

its at this point i feel like scrapping it all and starting again, it worked as it should until i tried to get it to read logs from nitrado, so i could add command in later but its not playing ball now haha

hearty basalt
#

but if it's sumn nitrado related i can't help cs i ain ever touch it befo

mental eagle
#

client = commands.Bot(command_prefix="/"), intents=intents

this is the line of code

client = commands.Bot(command_prefix="/"), intents=intents
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

this is the error...

#

i have tried == and := but still errors out

slate swan
#

what do you think that this part of code does? pithink

slate swan
#

commands the bot to do what?

mental eagle
#

the funny thing is

#

this is erroring on the part of the bot tha actually worked yesterday

#

@client.event
async def on_ready():
print("the bot is now ready for use")
print ("----------------------------")

@client.command()
async def goat(ctx):
await ctx.send ("CR7 SIUUU VAMOS PORTUGAL")

slate swan
#

yeah, for sure it didn't work yesterday if it was exactly what you sent

#

the intents kwarg should be passed as an argument in the place where you initialize the bot, just like command_prefix

#

!d discord.ext.commands.Bot

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.
mental eagle
slate swan
#

then you would probably also get some error because client is not defined

mental eagle
#

guess who feels like a prized tit now

#

its working

#

after removing the line that was giving the error... because there was nothing after the line of code except yesterdays command

slate swan
#

đŸ€·â€â™‚ïž you probably have a client defined somewhere else if it works

mental eagle
#

i say works, the bot goes online without any errors, but it progress

hearty basalt
#

you put it outside, i legit gave you my code 😭

#

fuck i'm spoonfeeding

mental eagle
hearty basalt
#

yh but i shouldntve spoonfed lmao it's against the rules

mental eagle
#

there's rules? haha

#

this is all new to me đŸ€­

hearty basalt
#

i mean idk if it's an actual written rule but it's a bad habit

#

it's better to learn rather than copy and paste code without actually understanding your mistakes

hearty basalt
mental eagle
hearty basalt
#

gave a description of what description does

#

that sounds weird

slate swan
#

It is just a description for the bot, I don't think that its used anywhere by d.py

hearty basalt
#

yh but i was wondering where it actually appears

slate swan
#

discord.commands.ext.BotBase.__init__

hearty basalt
#

The content prefixed into the default help message.
help_command: Optional[.HelpCommand]

#

but i have help_command set to None

#

so ion need it rahh

hearty basalt
#

would this work?

@tasks.loop(minutes=30)
async def countLoop():
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers"))```
rugged shadow
#

considering that it's every 30 mins

#

i think you should be good

crystal flint
limber jolt
#

Can I have some ehlp making slash commands?

#

Help*

hearty basalt
limber jolt
#

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

hearty basalt
#

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

hearty basalt
#

if it's not that long

limber jolt
#

Is got some other things as Its a bot for other things

hearty basalt
#

i use @bot.tree.command

limber jolt
#

Can you give me the code iN context?

hearty basalt
#
@bot.tree.command(name='slash', description='this is a slash command')
async def slash(interaction:discord.Interaction):
  # your logic

then you can either do await bot.tree.sync() in your on_ready() event, or make a separate command for it

#

then you can do interaction.response.send_message() to reply back

#

atleast this is how i do slash commands, i've seen others do it differently idk :p

limber jolt
limber jolt
# hearty basalt send your command

@bot.tree.command(name='slash', description='this is a slash command')
async def slash(interaction:discord.Interaction):
  interaction.response.send_message('This Is a slash command!')
#

It said It was correct until It underlined hwen I ran It but It all worked as normal until I did the command In discord

hearty basalt
#

does it say anything in the console?

#

you didn't await the response

limber jolt
limber jolt
#

Yes I did

#

OHHHHH

hearty basalt
#

from your code:

await message.channel.send

this is the same, you gotta await it :p

limber jolt
hearty basalt
#

use the ephemeral argument

#

it accepts boolean

limber jolt
sly hamlet
#
    @app_commands.command(name='purge',
                           description="Will delete messages.")
    @app_commands.checks.has_permissions(manage_messages=True)
    async def purge(self, interaction: discord.Interaction, limit: int):
            await interaction.response.defer()
            await interaction.channel.purge(limit=limit)
            em = discord.Embed(color=0x050505)
            em.add_field(name=f'Purge', value='Cleared by {}'.format(interaction.user.mention))
            
            await interaction.followup.send(embed=em)```
#

For some reason my purge command doesn't seem to want to send the message at the very end

#

No air other than this interaction failed to respond

slate swan
sly hamlet
hearty basalt
hushed galleon
sly hamlet
#

Half of the command works but the other half does not when trying to send the message

hushed galleon
#

oh, so it didnt show "failed to respond"?

sly hamlet
hushed galleon
#

i think the purge deleted your thinking message then, try what joris suggested

#

when you defer a slash command, it essentially sends a message with that thinking appearance and can be deleted like any other message

sly hamlet
#

so py async def purge(self, interaction: discord.Interaction, limit: int, ephemeral):

hushed galleon
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
sly hamlet
#

ooooooo

#

Thx

normal bobcat
#

Anyone here know the command to implement games onto discord bots for the slash commands?

#

I probably worded this horribly but if I need to explain no problem

ornate ore
#

Hello! I am making a discord bot and im hosting it on my raspberry pi. I have remote access from my mac to my pi and when i close the command line the bot goes offline. How do I make it so it stays online?

normal bobcat
urban briar
#

this question might have been asked 346 times so let me ask for the 347th time. I have a bunch of commands' code written for my bot. How do i implement slash commands for all these commands such that none of the commands' functionality is changed? Will I have to write the same functions again (with adjustments to slash commands) or is it as simple as adding a decorator?

normal bobcat
#

Like I know slash commands uses like-

urban briar
upbeat otter
urban briar
#

ohh

#

a new lib required?

normal bobcat
upbeat otter
#

I'll list a few and try to link you to necessary resources in just a second

  • You need to change the decorators so Bot.tree.command(...)
  • Slash commands use an Interaction instead of the usual Context (or ctx)
  • Methods for sending responses through slash commands differ from such as ctx.send to Interaction.response.send_message(...)
  • You need to setup a message command or a setup_hook to sync your slash commands to the discord API
normal bobcat
#

Setup hook etc was created yes

fast osprey
#

You should not be syncing in setup_hook every time your bot starts

normal bobcat
#

It's not-

upbeat otter
normal bobcat
#

I mean it all works out, I just cannot get my game to work with my bot because I don't know the right command

#

Wait couldn't I just make a function for my game and then use the function name in the argument to run a slash command?

fast osprey
#

You should not be asking users to tell you which python functions to run lol

normal bobcat
#

._.

#

Nevermind.

#

Fuck asking for advice then

fast osprey
#

It depends on what you want the command to do really. You can present them with options to choose from

hushed galleon
latent jay
#

Anyway to change the default discord.Attachment message when annotated to a slash command?

#

the "Please attach a file.."

wanton current
#

nope

twilit grotto
#

worse case scenario type hint it to none if u want it to be optional

quick gust
#

typehint it to None?

upbeat otter
quick gust
#

đŸ€ 

#

but I think they mean param = None

torn solar
#

!paste

#

https://paste.pythondiscord.com/HFKQ

how can i get the interaction failed message to go away when i flip pages. everything is working fine with flipping pages but its giving me that message and its so annoying

urban briar
pale zenith
torn solar
# pale zenith You need to respond. Use interaction.response.edit_message instead of message.ed...
  File "C:\Users\teddy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\teddy\OneDrive\Desktop\new chase\drragon.py", line 126, in next_button
    await interaction.response.edit_message(embed=embed)
AttributeError: 'Button' object has no attribute 'response'```
#

await interaction.response.edit_message(embed=embed)

#
    async def next_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.current_page = min(self.current_page + 1, len(self.pages) - 1)
        embed = self.pages[self.current_page]
        await interaction.response.edit_message(embed=embed)```
elder tinsel
#

@bot1.command(pass_context=True)
async def dm(ctx, message):
guild = ctx.message.guild
for member in guild.members:
await asyncio.sleep(0)
try:
await bot.send_message(member, "This is a Test")
print("Sent message")
except:
pass

#

Im trying to get a bot to dm people

#

Any advice?

pale zenith
pale zenith
torn solar
#

swap interaction and button in the params?

pale zenith
#

Yes

torn solar
#

so interaction: discord.ui.Button

#

right

torn solar
pale zenith
#

The first Param will be the interaction and the second will be the button. You should swap their placements so the variables are named accordingly

torn solar
#

like that?

elder tinsel
torn solar
#

works great tysm

merry cliff
drifting arrow
fickle stag
#

Hello, I have a discord bot and I want to give it to someone, but I want them to use it without seeing the codes. How can I do it? Can you help me?

slender pecan
#

Hi, would you like to ask if it is possible to have different avatars for each server?

#

on bot

upbeat otter
slender pecan
#

how mee6

elder tinsel
#

So when i get a new partner i can run the script n it will send the ad to dms

slate swan
#

I like how most of the people want the bot to dm someone with any content without them giving a consent for stuff like that

shy eagle
#

what exactly do i type to define converter?

#

error says i havent defined converter

wanton current
#

show error

fickle stag
upbeat otter
wanton current
# slender pecan how mee6

mee6 basically makes you make your own bot and give them their token and they host an instance of mee6 on your token

#

meaning you can change the avatar and stuff, etc.

hearty basalt
#

im legit using a host for like $5/mo

fickle stag
upbeat otter
#

just saying

hearty basalt
#

yeah fr they started out at like 1 buck

#

i just got one with more ram

#

(i didn't need to 😭)

upbeat otter
hearty basalt
#

ill check

hearty basalt
upbeat otter
#

That's a lot

hearty basalt
#

legit $1/mo

fast osprey
#

Anyone considering any transfer of bot tokens should very carefully read the developer tos

charred island
#

is it possible to run bots sequentially? not asynchronously but sequentially. Ive a basic structure of bots that perform different things and whenever they recieve a signal one of them shuts down. I would like to switch the bot using another Authorization token of other bot and proceed with the actions

fast osprey
#

Why have bots at all? You could just hit the api and do what you want rather than waiting on a gateway connection

fast osprey
#

No, just api calls

charred island
#

Ahh, but how would I track messages then?

fast osprey
#

What does "track messages" mean?

charred island
#

like, using a bot I can call the on_message event

#

And part of my code relies on that.

#

"the signal"

#

How would I do the same with api? Messages history takes about 3-4 mins to refresh

fast osprey
#

What exactly are you trying to do, and why are multiple bots involved

#

"Sequential" implies bots going up and down, in which case they would not be listening for events

charred island
#

and then continue the operations

#

ofcourse i can do it from one bot but ive something else in mind and would like to switch regardless

fast osprey
#

You should really avoid building your bot relying on other bots you don't control behaving in specific ways

#

they make one minor, unannounced trivial change to their bot and everything you've built on top of it randomly breaks

#

You should also strongly consider why you would want to build and maintain separate interdependent bots for anything beyond cosmetic reasons

fast osprey
#

Sure, but if you don't care that your thing is going to break instead of putting in the minimal effort to harden it then that's your decision

zinc gust
#

basically im doing a discord bot that does a button and once you click the button it gives u a role that make u able to see the other channels, but i dont know why my button is disabling itself after clicking on it, and when someone leave and rejoin the server, he cant click it back. here is my code

fast osprey
#

Nothing in here would edit the message that button is on

elder tinsel
slate swan
#

and you think that they want it? pithink

elder tinsel
#

Its not about that. They can block the bot

#

Thats their business

fast osprey
#

That isn't how this works

#

You cannot buck the responsibility on to the user for your bot harassing them

elder tinsel
#

Ok? How do i get it to dm certain people then

fast osprey
#

That have said they want to be dm'd?

slate swan
#

tbh I would just make a command that allows user to disable or enable those ad dms

elder tinsel
#

Like i could give a user id or a role

elder tinsel
slate swan
#

by default it should be disabled and you could store if they agree to it or not somewhere like a DB, cache or whatever

elder tinsel
#

Bc i could do it where when the user uses the help cmd it dms them the cmds

#

Just to keep from flooding chat n shit

fast osprey
#
  1. Do not target users with advertisements or marketing. Messaging to Discord users from any Application or developer team should be relevant to the function of the Application and may not contain material unrelated to an Application’s function or information.
elder tinsel
#

Ive seen some bots do it n thought it was kinda cool

elder tinsel
#

I jus want it to dm the list of cmds when they type the help cmd

fast osprey
#

It's recommended instead that you make this as a slash command with an ephemeral response

#

which wouldn't even need a help command as it documents the commands for you

elder tinsel
#

See i typed the r word n python bot dmed me

#

Also i do not know wtf ephemeral is

fast osprey
#

discord slash command ephemeral google is your friend

#

But basically a way of answering a command with a message only the invoking user can see where they ran the command

elder tinsel
#

So does that happen in the server

#

Or will it dm them

slate swan
#

Ephermeral messages can be sent in dms and in servers and the message will be only seen by the person who trigerred / invoked the command

#

iirc

hearty basalt
#

a bot can send ephemeral messages as a DM?

slate swan
#

I just checked the docs and actually not

hearty basalt
#

wouldn't really make much sense lol

slate swan
#

true

elder tinsel
#

But dms is the goal so how do i achieve that?

hearty basalt
#

i mean you could jus use on_member_join(member)

slate swan
#

Something as simple as that should work

#

for the command that allows users to decide if they want to receive dms

#

0 would be False and 1 would be True

wanton current
#

that's one confusing schema

slate swan
#

true but hopefully they kind of got it

hearty basalt
#

not really that confusing

slate swan
#

didnt spend much time on it which you can see ducky_yellow

slate swan
fast osprey
zinc gust
slate swan
#

never mind

hearty basalt
wanton current
hearty basalt
#

chat rn i'm using this in my on_ready():

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers <3"))

how can i update the len(bot.guilds) when the bot joins / leaves a guild? i tried creating a global variable in the on_guild_join event but it just removes the status completely instead of updating it

#

and i also tried changing the whole presence in the on_guild_join too

fast osprey
#

You should not be using on_ready to do things you want done once

#

Also you should reconsider humblebragging in your bot's status instead of using for useful information

hearty basalt
#

"humblebragging" is a humongous reach instead of actually helping lmao

#

li twan wiggin

hearty basalt
fast osprey
#

Not sure how else you want to categorize something that gives 0 helpful information besides broadcasting to people how popular your bot is

#

This endpoint is potentially rate limited harder than these events would fire in practical purposes

dry kelp
#

Why is it still not displaying the nitroboost emoji?
Because that's not an issue of my emoji mapper

#
    def get_badges(self, real_user, user) -> str:
        badge = ""
        if guess_nitro(real_user):
            badge += self.e("nitro")

        if user.premium_since:
            badge += self.e("nitroboost")

        # Mapper for user badges
        mapper = {
            "bug_hunter": self.e("bughunter"),
            "bug_hunter_level_2": self.e("goldbughunter"),
            "hypesquad_bravery": self.e("bravery"),
            "hypesquad_balance": self.e("balance"),
            "hypesquad_brilliance": self.e("brilliance"),
            "hypesquad": self.e("hype"),
            "early_support": self.e("earlysupporter"),
            "early_verified_bot_developer": self.e("verifieddev"),
            "verified_bot": self.e("verifiedbot"),
            "staff": self.e("staff"),
            "partner": self.e("partner"),
        }

        # Use advanced_map_kv to map user public flags to badges
        badge += " ".join(advanced_map_kv(mapper, user.public_flags))

        return badge or "None"
#
def advanced_map_kv(mapper: Dict[str, str], struc: Any) -> Iterator[str]:
    return filter(
        lambda z: z is not None,
        map(
            lambda v: mapper.get(v[0], ""),
            filter(lambda k: k[1], dict(struc).items()),
        ),
    )
elder tinsel
hearty basalt
#

wouldnt member.send work?

#

seeing as on_member_join() only accepts member as a valid parameter

fast osprey
#

Someone can't possibly consent to you dming them by just joining a guild

hearty basalt
#

im not encouraging it but it's not like no bot ever does it lol

dry kelp
#

You have early supporter badge, I would be appreciating you if we can test out something

fast osprey
#

Someone doing something is pretty irrelevant when considering whether or not you should do something or tell someone else how to do it

#

It's also a pretty fast way to get your bot locked out of the api for spam, morals aside

dry kelp
fast osprey
#

You can't limit people reporting you for dming them unsolicited

dry kelp
#

You can also check if that user already received the message and set a interval to not send again

hearty basalt
#

have you never been DMd by a bot after joining a server before lmao

fast osprey
#

And I report them every time

hearty basalt
#

...

dry kelp
#

For example i know pro bot has that, You can customly set it up in they're dashboard

fast osprey
#

The guild manager can't decide for individual users whether or not they want to be harassed

hearty basalt
#

shi i joined one server n got like four bots dmin me

#

but it's life

#

i mean it's up to you what you wanna do shrug

fast osprey
#

People doing it is not a signal that it's okay to do

dry kelp
fast osprey
#

There are, but what does that matter to the conversation

dry kelp
#

Solstice i have sent you a message.

hearty basalt
#

'harassed' is also a wild claim

fast osprey
#

Do you want to pull up the definition of the word

dry kelp
hearty basalt
#

ain like the bot spams DMs

fast osprey
#

I'm not going to argue with you on the definition of words when both the developer policy and the existence of unpublished api flags make this very clear

hearty basalt
#

ite

outer violet
#

okay i need help. i cant figure out why this is happening. i did some tests by changing the name of a channel: test 1 was creating it, test 2 was changing the name for the first time, and test 3 was changing the name again. the update_type for test 2 keeps saying "Topic" when its supposed to say "Name" like how test 3 is. i never changed the topic, i only changed the name. can someone help help? its supposed to display the correct update_type but it's not

i use hikari-py. this is my code: https://pastes.dev/RUCqPhrbIJ

elder tinsel
upbeat otter
elder tinsel
outer violet
#

my event needs to correctly identify what specific attribute of the channel was changed (update_type) and then log the relevant details. test 2 is incorrectly identifying what attribute was changed since it says "Topic" when it should be saying "Name", since i only changed the name

slate swan
#

hi

#

is there free hosting for my python discord bot

outer violet
#

used this at one point https://daki.cc/

fast osprey
#

Free hosts are universally scams. Randos are not going to pay their own money to run your stuff for you, there is always a catch

#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

hushed galleon
outer violet
outer violet
hushed galleon
#

have you tried printing before_topic and after_topic?

outer violet
hushed galleon
unkempt canyonBOT
#

hikari/impl/entity_factory.py line 1082

topic=payload["topic"],```
outer violet
#

so how do i fix it

hushed galleon
#

one is None, the other is an empty string

#

you should update your condition so they're both considered equal

hearty basalt
outer violet
#

LETS GO IT WORKED

elder tinsel
#

@bot1.command(pass_context=True)
async def dm(ctx, message):
guild = ctx.message.guild
for member in guild.members:
await asyncio.sleep(0)
try:
await member.send("This is a Test")
print("Sent message")
except:
pass

unkempt galleon
#

raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

#

does anybody know hw to fix that error

fast osprey
#

On mac?

unkempt galleon
#

now im getting this error

#

File "C:\Users\Administrator\Desktop\discord-bot-main\boosting.py", line 99, in fingerprint_modification
properties = fingerprints[0]['x-super-properties'] = 'aWYgb3MubmFtZSA9PSAibnQiOgogICAgY3R5cGVzLndpbmRsbC5rZXJuZWwzMi5TZXRDb25zb2xlVGl0bGVXKGYiSWYgeW91IGJvdWdodCB0aGlzIHlvdSBnb3Qgc2NhbW1lZCB8IGdpdGh1Yi5jb20vUGl4ZW5zIikKICAgIGZvciBpIGluIHJhbmdlKDEwKToKICAgICAgICBwcmludCgiSWYgeW91IGJvdWdodCB0aGlzIHlvdSBnb3Qgc2NhbW1lZCB8IGdpdGh1Yi5jb20vUGl4ZW5zIikgICAKZWxzZToKICAgIGZvciBpIGluIHJhbmdlKDEwKToKICAgICAgICBwcmludCgiSWYgeW91IGJvdWdodCB0aGlzIHlvdSBnb3Qgc2NhbW1lZCB8IGdpdGh1Yi5jb20vUGl4ZW5zIikgICAgICAgICAgIAogICAgICAgIA=='
~~~~~~~~~~~~^^^
KeyError: 0

meager dagger
#

How could I make a bot that deletes every discord message I've sent in a server? (or better yet, on discord as a whole)

fast osprey
#

You would file a request with discord

meager dagger
#

How does one do that?

fast osprey
#

File a ticket with their trust & safety team

meager dagger
#

Not seeing anything on their ticket site that says anything about that

elder tinsel
hearty basalt
#

dming every user on command is WILD

#

what is that asyncio.sleep(0) even for?

elder tinsel
elder tinsel
#

Idk how to do the shit

hearty basalt
#

thats what that command does

elder tinsel
#

It doesnt even dm anyone 😭

hearty basalt
#

then perhaps i am smoothbrained

slim bloom
#

Is there some type of sqlite3 but encrypted?

elder tinsel
#

I think i am

fast osprey
hearty basalt
elder tinsel
#

I just want to actually send a dm

#

Then ill decide about makin it dm upon joinin

slim bloom
#

Is there some type of sqlite3 but encrypted?

hearty basalt
#

i mean im still kinda new but im pretty sure

 for member in guild.members:
   await member.send("This is a Test")

would dm every user wouldn't it?

elder tinsel
#

Dude idk

#

Im like the only person in my test server so it dont even matter

#

As long as i get it to dm someone

elder tinsel
pale zenith
fast osprey
#

Worth a shot shrug

hushed galleon
slate swan
#
import discord
from discord.ext import commands
from config import TOKEN

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

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

@bot.event
async def on_ready():
  await bot.tree.sync()
  print(f"Logged in as {bot.user}")
  
  
@bot.hybrid_command(description="test")
async def helpme(ctx):
  await ctx.send("No commands yet since the bot is still in testing")  
  
@bot.event
async def on_ready():
  await bot.tree.sync()
  print(f'Logged in as {bot.user}')
  
bot.run(TOKEN)
  

why doesn't it register as a slash command

merry cliff
# slate swan ```py import discord from discord.ext import commands from config import TOKEN ...

after you run the code, ctrl + r to refresh your discord and see if it pops up. I also recommend not syncing your commandtree in on_ready as that can be triggered multiple times which would essentially spam the discord API. Instead I recommend doing it in setup_hook which only runs once.

@bot.event
async def setup_hook():
    print("syncing slash commands...")
    await bot.tree.sync(guild=None)  # global sync```
slate swan
merry cliff
slate swan
#

oo alr thx

merry cliff
#

np

slate swan
slate swan
#

thx

outer violet
#

i have weird formatting again but this time with my GuildMessageDeleteEvent. i got the mod who deleted the users message (kind of??) using list(entry.users.values())[0] but now when a user deletes their own message, it says a mod did it when its not supposed to. the bottom embed in the left photo is what it looks like when a mod (me) deletes another users message which works fine. the top embed in the left photo is supposed to look like the right photo but it says "deleted by moderator"

code: https://pastes.dev/yGSzIPzfZF

elder tinsel
#

So its not even deleting my msg. So it wont delete the msg which i dont care about but it wont dm.

#

@bot1.command(pass_context=True)
async def dm(ctx, message):
await ctx.message.delete
guild = ctx.message.guild
for member in guild.members:
try:
await member.send(message, "This is a Test")
except:
pass

golden portal
#

mass dm is against tos, and there is a reason why bare try-except is a bad practice, i mean you can't see the error

outer violet
elder tinsel
outer violet
#

Well you’re not calling the delete method so it won’t work

#

It won’t perform any action

golden portal
elder tinsel
elder tinsel
outer violet
elder tinsel
outer violet
#

By calling the delete method, you need delete()

#

You haven’t called it

#

So it won’t delete

elder tinsel
#

Fixed that but the dm

outer violet
#

You also don’t pass any user or role argument in your command

#

So it can’t dm anyone

upbeat otter
# elder tinsel Fixed that but the dm

Get the members of a role either through Guild.roles or you can fetch them (search the docs)

You will then have a list of Role objects. You can loop over these and access the member objects and then dm them

outer violet
#

Do you know python

#

You say you want to dm specific role or user but you don’t have role or user as arguments

elder tinsel
#

Im tryna learn

outer violet
#

Get the member by using get_member()

elder tinsel
outer violet
#

If statement works

outer violet
#

You need to define member

#

member = guild.get_member(user.id)

outer violet
# elder tinsel Barely anything

You should learn python first. Bot dev is gonna be hard if you barely know anything about python. This is a good video https://youtu.be/rfscVS0vtbw?si=fntPYd31cOQ0m8R9

This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!

Click the ⚙ to change to a dub track in Spanish, Arabic, or Portuguese, or Hindi.
(Hindi dubbed via Melt Labs - https://www.withmelt.com/)

Want more from Mike? He's starting a codin...

▶ Play video
elder tinsel
#

Dude its jus that everything changed in the last 4 years

golden portal
#

tbh, 4 years ago and now have the same approach

outer violet
#

I’m pretty sure it’s still usable material

elder tinsel
#

Not really used to be that dm script worked or least it did for me

golden portal
#

I can guarantee it would've raised an error, 4 years ago was 1.x and not much has changed beside new features

elder tinsel
#

Fr?

#

@bot1.command(pass_context=True)
async def dm(ctx, message):
guild = ctx.message.guild
for member in guild.members:
await asyncio.sleep(0)
try:
await bot.send_message(member, "This is a Test")
print("Sent message")
except:
pass

elder tinsel
quick gust
#

pass_context isnt used anymore I believe?

outer violet
#

Nope

elder tinsel
#

Even then that shit still dont work

outer violet
#

It’s really outdated

golden portal
#

That would be 0.16.x

#

Which is actually 5-6 years ago

elder tinsel
#

Nope

outer violet
north kiln
#

do you even have message content intent

hot stump
fast osprey
#

I don't think people are going to invite a random bot to their server, you should just post the code if you want feedback

hot stump
#

send a copyright free SVG file and ill add for u

rugged shadow
#

easy way to get sued by nickelodeon

foggy lake
#

can anyone help me with embed images, i m new..

drifting arrow
#

There's several spots you can put an image in an embed.

#

So depending on where you want it will determine what embed thing you use

#

Ultimately you need a URL of the image

subtle jolt
#

Is there something similar to @commands.Bot().after_invoke for app commands in discord.py?

wanton current
#

what's your goal?

subtle jolt
#

to increment a commands ran stat for the user

wanton current
#

there isn't anything similar no afaik

#

could use on_interaction and check if it's a slash command or make your own decorator perhaps

turbid shard
#

this might sound weird but... does anyone know how to do a sub-subcommand?
such as
/settings set key
/settings set blabla
/settings set whatever

subtle jolt
turbid shard
turbid shard
subtle jolt
turbid shard
#

oh

turbid shard
# subtle jolt `app_commands.Group`

well i have this for settings

command_group = app_commands.Group(name="settings", description="Settings")
bot.tree.add_command(command_group)

do i just... create another command_group under settings?

subtle jolt
#

sub_command_group = app_commands.Group(name="set", description="Set", parent=command_group)

#

i think

turbid shard
#

what the androidsob

#

you forgot to close the ) btw

subtle jolt
#

no linting in discord code blocks 😉

untold carbon
turbid shard
wanton current
#

for what

midnight oracle
turbid shard
wanton current
hushed galleon
#

oh they left

keen lynx
#

is there any bot which can ping developer when bot goes offline?

fringe prairie
hearty basalt
#

you reckon you could check a bot's status with another bot lol

#

can you get a user's status? as in online/idle/dnd/invis

upbeat otter
#

can use the presence event for that

fringe prairie
slate swan
normal linden
#

i need help with scraping , who is good at it pls dm / ping

slate swan
#

what do you need to scrape

#

html? text? code? images? links?

blazing beacon
#

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

blazing beacon
#

?

#

(apologies if this rule doesnt apply)

upbeat otter
#

yeah it doesnt 💀

fast osprey
#

There is a very very small percentage of services that allow for scraping in their terms of service

oblique harness
blazing beacon
blazing beacon
oblique harness
wanton current
#

did u read rule 1

oblique harness
#

ain't no way ppl will read a page of rules !!

wanton current
#

ikr

oblique harness
#

nowadays servers are becoming trash and abusing most of their members, why in hell would they put the lgbtq shit flags on the server logo not all ppl support that sick shit it honestly looks disgusting

wanton current
#

did bro get banned or leave

merry cliff
#

Idk

blazing beacon
lyric night
#

I was trying to scrape a website and in order to open the necessary pop-up to scrape, i first need my program to click somwhere on the screen (a button) to open the pop-up. I am using selenium and the webdriver but when my program opens the website and is supposed to click on specific coordinates it doesnt do anything. Also why does the tab close after a bit? Is it just because the program couldnt work or is it a timeout or something?

fast osprey
#

Which website?

twilit grotto
twilit grotto
#

u can read more on it there

#

just set a high timeout i guess

drifting arrow
#

never not 999

#

If in doubt, add another 9!

elder tinsel
#

Genuine question. Can someone get my account token if i accept their friend request? Bc i jus got a sus ass request

drifting arrow
#

If it's just a friend request on discord? No.

drifting arrow
elder tinsel
#

Ight

drifting arrow
#

If you do go to a website, and it prompts you to log in, the login prompt should always be on a new tab, but if it is in a pop-up window, the window should be able to be freely moved outside of that browser window.

drifting arrow
#

That video demonstrates that it's not a legitimate website asking you to log in because that additional window cannot be moved outside of that website. Meaning they're capturing your login details as you type it.

elder tinsel
#

Cuz this looks sus asf

drifting arrow
#

What I normally do whenever I get random friend requests is, I first check mutual servers and friends.

#

If there's no reason for them to add you without mutuals, then it's probably a scam, so be on alert.

Then you can simply ask them what's up. Give them an opportunity to explain why they added you

#

As long as you dont click links or download anything you'll be fine

elder tinsel
#

Bet

golden portal
#

i click every link that a random person sends

drifting arrow
#

What you do with your last remaining brain cell is entirely up to you @golden portal

golden portal
#

(real)

torn solar
#

!paste

#

can someone help me make this persistent? ive tried but failed

#

@pale zenith sorry for ping but you were available at same time last night

#

2 nights ago

hearty basalt
#

i think

#

oh wait yours is a bit different idk

pale zenith
#

Jokes on you my sleep schedule is too shit! I just woke up

#

Breakfast first and if it hasn't been solved I'll check it out

hearty basalt
#

man px

fast osprey
drifting arrow
drifting arrow
pale zenith
# torn solar can someone help me make this persistent? ive tried but failed

The main problem you'll face when trying to turn this view into a persistent one is the fact that you're passing state to it when initialising it, and you won't have that available at startup. The easiest way to mitigate this persistent is by using a discord.ui.DynamicItem (example usage), which is only available in the beta release of discord.py for now (pip install git+https://github.com/rapptz/discord.py). With this, you would store the offer ID inside of the view's custom ID, and then fetch the rest of the necessary info inside the from_custom_id from your database (for when it is persistent).

pale zenith
clear lark
#

Is it possible to make @discord.app_commands.describe() optional? I don't see anything in the docs, but want to check

clear lark
#

optional for the user to fill in

drifting arrow
#

Like once the bots running?

clear lark
#

Huh? How is that related?

#

I mean if the command /example can take two separate text inputs (.describe) the first is required, but the second is not

drifting arrow
#

You can't change it while the bot is running, well you can, it's just not worth the effort.
But you can make it easier for the end user to configure it by moving the string to a variable and then importing it from a config file

clear lark
#

Thats not what I'm talking about

drifting arrow
#

oh

#

Just set their value to none

#
#Creates the slash command
@discord.app_commands.command(name="fake_command", description="A fake command")
#Sets it to only work in guilds not private messages
@discord.app_commands.guild_only()
#Sets a description for each paramater the command takes
@discord.app_commands.describe(required_param="This param is required.", not_required_param="This param is not required.")
#Unique name for the commands function (duplicate functions will always default to the last one loaded)
async def my_fake_command(self, interaction:discord.Interaction, required_param:str, not_required_param:str=None) -> None:
#stuff goes here
clear lark
#

Thank you

drifting arrow
#

No problem

#

I put the full decorator locations for you. But you might not need them

#

as I usually import specifics

#

ignore the squigglies. New computer. Pylance is being a noob

clear lark
drifting arrow
#

Don't call yourself dumb lol. We all make mistakes

#

I was you not too long ago

clear lark
#

Nothing wrong with doing something dumb, just means I'll do better next time

drifting arrow
#

You just learn 1 extra way of how not to do something :)

#

Like, for example. I am currently trying to connect to my friends server which is in a pterodactyl container.. I'm learning a lot about files and shit. Like did you know if the file is too big you can't just view it, you have to download it?
and if the files being actively written to you have to then figure something else out?

#

:D such fun

clear lark
#

That is actually something I knew, and from what I recall (its been quite a while since I've done anything with servers/web) it is not fun to deal with

drifting arrow
#

nope.

#

So I'm going to try making a copy of the file directly on the server and just downloading that file instead

clear lark
#

If it works, it works

drifting arrow
#

hopefully

#

fingies crossed!

#

First I gotta get my bot back to the state it was before I needed a new computer lol

#

And then refactor some code ;-;

clear lark
#

Refactoring always manages to kick me in the ass, even with Pycharm

drifting arrow
#

:D

clear lark
#

I wish you luck

drifting arrow
fast osprey
drifting arrow
#

:( aiohttp.client_exceptions.ClientPayloadError: Response payload is not completed: <ContentLengthError: 400, message='Not enough data for satisfy content length header.'>

#

NOT ENOUGH GIRTH

wanton current
#

damn

shy eagle
#
async def on_message_create(message):
    if not message.guild:
        return
    if message.channel.id == 1252931571388907570: # suggestion channel id
        await message.add_reaction("👍")
        await message.add_reaction("👎")```
#

this code does not work althought there are no errors..

#

it doesnt add the reactions

finite salmon
#

but on_message exists

shy eagle
#

k one sec

shy eagle
finite salmon
#

any errors?

timber dragon
#

Maybe check the id you're comparing..

shy eagle
#

No errors

#

The id is the correct channel

fast osprey
#

Code?

pine mortar
#

I'm considering buying a raspberry pi 4 1GB and a micro SD card of 64GB (Cheapest I could find ironically enough.) to host my (node.js) discord bot, but before I do that, does anyone have a better solution such as a free VPS with good specs or any cheaper options to buy a Raspberry Pi 4 1GB (or 2GB) or an SSD that ships cheap to the Netherlands? Right now I have an online shop that sells the raspberry pi for 39.85 and a real life store near me that sells the SD for 8.87.

fast osprey
#

No such thing as a reliable eternally free host, that would be an unsustainable business model

hearty basalt
#

idk what specs you need

fast osprey
#

That service is incredibly bad

hearty basalt
#

ok

#

giliai px

wanton current
fast osprey
#

Pretty sure that's the one whose site got flagged for me by avast?

hearty basalt
#

yall wiggin

odd dagger
#

hi

#

why does the terminal tell me this please

hearty basalt
odd dagger
#

do u have the solution of my probleme ?

shy eagle
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'avatar_url'```
#

got this error

hearty basalt
shy eagle
#

yes

hearty basalt
#

it's guild.icon

shy eagle
#

kk

odd dagger
#

..

sick birch
midnight oracle
#

you do have Python installed but it's not selected to run the code I guess

fast osprey
#

On windows ideally all python invocations go through the py launcher

odd dagger
limber jolt
fast osprey
#

Replit is not a suitable environment for running bots

limber jolt
slate swan
#

Google is your friend

limber jolt
slate swan
#

Well, there are countless tutorials on the internet if you take some few minutes to search

limber jolt
#

Use VS code they say

#

It will be easy

#

You cant even import discord

#

some bs

hearty basalt
limber jolt
hearty basalt
limber jolt
hearty basalt
#

idk atleast that's how i did it

limber jolt
hearty basalt
#

huh

#

i might be too slow to understand that sentence

#

given we're in the python discord

limber jolt
hearty basalt
slate swan
limber jolt
slate swan
#

that is the reason for PIP to exist, to install packages/libraries

hearty basalt
#

so you want it to work without installing it?

#

folk thats like being angry your car wont run when it doesnt have an engine 😭

slate swan
#

Im pretty sure that you have to install discord.py on replit aswell with PIP

#

iirc

#

so I don't see what is the difficulty

hearty basalt
#

typing one line into the cmd isnt that difficult

limber jolt
limber jolt
hearty basalt
#

restart vscode if you didnt after pip installing it

slate swan
#

what exactly is the command that you are typing? It's:

pip install <package/library name>
pale haven
#

Can anyone help me?

slate swan
#

with?

limber jolt
#

Ugh can someone just send me a vid cuz I need more sleep for this

#

nvm

#

I think I found one thats still In date

pale haven
#

my bot discord

slate swan
pale haven
slate swan
#

that is discord.js, not discord.py or any other python API wrapper for discord

midnight oracle
#

Hyo! I'm finishing a user-info feature for one of my bots aand I kinda got lost tryng to find which interaction I want to access. The thing is, when a user joins the server, the bot sends a message asking him some questions, right now this is "started" with a Button and the questions with SelectDropdowns but when they finish I want to edit the first message and delete the dropdown message (image attch of how it ends right now, I want to delete the one woth the Selects), I've done the first thing but the second I don't know which interaction or where to access it to delete the message. Here the code :D

https://paste.pythondiscord.com/7C7Q

sturdy egret
#

yo gang

#

any clue how to fix this:

#
TypeError: Webhook.send() missing 1 required positional argument: 'self'
fast osprey
#

You're probably calling it on the class and not on an instance of Webhook

fast osprey
# midnight oracle Hyo! I'm finishing a user-info feature for one of my bots aand I kinda got lost ...

Firstly, you shouldn't be sending people messages unsolicited.

Second, there's really no functional reason for these to be two separate messages, your code will be a lot messier trying to do it that way. If a component is interacted with, it really should only need to modify the message it's on. You can pass messages around if you want to (not interactions) but this is kind of overcomplicating it when that could just be on one message

sturdy egret
#

AttributeError: 'NoneType' object has no attribute 'send' i keep getting this error

#
                    await messagechannelID.send(
                        view=ButtonSendCode(),
                    )
#

Code im using to do it

#

responsewebhook = requests.get(data["webhook"])
datawebhook = response.json()
messagechannelID = datawebhook.get('channel_id')

#

and that to find the webhook

fast osprey