#discord-bots

1 messages · Page 316 of 1

golden portal
#

a specific emoji?

hallow kernel
#

All

#

Like
If they join but yet not passed the verification, they won't be able to use my emojis

slate swan
#

how can i add slash commands to my bot?

golden portal
golden portal
slate swan
#

oh, thanks

#

Do you also have a doc ab reaction roles too by any chance?

hallow kernel
slate swan
golden portal
#

since guild.roles always contain everyone role, and it's the first element, you can slice it

hallow kernel
#

i dont mean
External emojis on my server
I mean
My emojis on other servers

golden portal
#

pretty sure if they dont have the role in your server it wouldnt work on other server as well

#

i forgot though so i cant test

white citrus
#

how can I make my bot an authorized app?

rotund flame
#

What do u mean?

white citrus
#

Like this

rotund flame
#

There is a Verified Bots topic

#

But dont say any requirements

#

I saw also that for a bot that is in more than 100 server it has to be verified to get in another one

solar glen
#

there isn't anything to show, i just need a way to make a url where it contains the bytes of a image or use some other method for again using bytes on a avatar

#

like if u wanna the read process of how im getting the bytes, ig here

#
#...
async def foo(attachement: discord.Attachement)
  contents = await attachement.read()
  # Processing...
  return contents

# When they want to execute a specific command
async def bar(data):
   # Making the webhook
   avatarBytes = ...
   # Processing...
   await webhook.send(avatar_url = avatarBytes) # Or some other method that i don't know for creating a avatar
wicked atlas
white citrus
wicked atlas
#

what for?

cold sonnet
#

self bot

#

duh

#

nah jk

wicked atlas
#

afaik you can't selfbot using oauth2

cold sonnet
#

I have no idea

white citrus
#

For Dashboard

shrewd apex
#

discord documents it's oauth flow how it works is u create a callback url in bot app which points to url in ur website and get users acess token and refresh token and use those to validate requests

cold sonnet
#

Asher writing a paragraph

shrewd apex
#

one para not enough to document discord oauth flow 💀

wicked atlas
#

that's why they have a whole page of documentation for it

cold sonnet
#

trenything is possible

white citrus
#

from discord.ext.ipc import Server

In a tutorial he use this. But i use nextcord. How is it called in nextcord?

cold sonnet
#

the what

#

is this new

shrewd fjord
#

its a thirdparty module no?

shrewd apex
#

what library is the tutorial using?

shrewd fjord
#

why would it even exist in python discord

shrewd apex
#

i have no idea haven't done discord bots in a while

white citrus
cold sonnet
#

bruh

shrewd apex
#

bro write your own implementation 💀

shrewd fjord
shrewd apex
#

u probably don't want to use pure python for a dashboard either

#

at best for backend api

cold sonnet
#

challenge accepted

shrewd apex
#

sure hab fun you have to resort to js for a lot of front end interactivity either ways

cold sonnet
#

did I not say challenge accepted

shrewd fjord
#

xd

#

thats another challenge tbh

cold sonnet
#

write data in text file

wicked atlas
#

apis

shrewd apex
cold sonnet
#

read data from text file

#

text file = db

shrewd fjord
#

it wont solve your all problems tho

#

hmm maybe we can store bot token in both side

shrewd apex
#

depending on what data you want ideally the data can should be fetched based on scopes you asked for that can be done in website itself

shrewd fjord
#

yeah then just need to store the bot token?

shrewd apex
#

if you want data outside scope make endpoints or run a webserver along with your bot

#

depends on how you structure your project

shrewd apex
#

iirc for plain oauth u dont need bot token right?

shrewd fjord
shrewd apex
#

guild scope is there for that right

shrewd fjord
#

there is but wait\

#

nah fk you just store the acces token 💀

#

brain not braining

cold sonnet
#

what brain

#

I got so lost when asher started talking

shrewd apex
cold sonnet
#

nah I was already lost when I saw discord.ext.ipc

shrewd apex
#

fair

shrewd fjord
white citrus
#

Can someone enlighten me xD

cold sonnet
#

nah bro you enlighten me first

#

is ipc already just your 3rd party lib

#

yeah that doesn't tell me none

shrewd apex
white citrus
shrewd apex
#

js, python etc what are u familiar with

white citrus
#

Python and html

shrewd apex
#

do you have a db?

white citrus
#

Yeah

shrewd apex
#

so pick some library like django or fastapi

white citrus
bleak perch
#

1

#

2

hushed galleon
solar glen
#

oki dokie

#

it kinda raises a problem

#

since i need the bytes to recustomise the webhook's avatar

#

i don't have a attachement

#

i only have the bytes of it

naive briar
#

Can you do it similarly to embed's attachment:// way? I wonder

patent lark
#

Can i invoke a subcommand from Jishaku Inside of another command?

#

@hushed galleon?

fading marlin
#

Flip the arguments around in your button callback:
(button, interaction) -> (interaction, button)

vapid parcel
#

Question, does anyone know if you can make your bot use an app command from another bot?

#

or would that be against ToS..? or is that even possible?

fading marlin
#

Not possible due to Discord limitation

vapid parcel
#

Damn.

#

not even if you used the command ID?

fading marlin
#

Nope

vapid parcel
#

Dang

#

That sucks ig

fading marlin
#

Most bots don't let other bots interact with eachother either way, so 🤷

vapid parcel
#

I mean fair

#

Just wondering if it was even possible

stark nexus
#

Anything could help me a problem with cog?

final iron
#

I also don’t see why you’re awaiting an append method

vapid parcel
#

Is that possible? to have a boost channel? kinda like a welcome and leave message?

#

if so, whats the docs for it

stark nexus
vapid parcel
#

embedding looks better compared to what discord does :/

sick birch
#

What's the problem, then? You just send the embed to whatever channel you want

vapid parcel
#

what event would it be?

#

we have on_member_join an on_member_remove now what about something like on_member_boost or something? which i know on_member_boost isnt a thing, so wondering a way to do it..?

sick birch
vapid parcel
#

huh

#

how so?

sick birch
#

you get an on_message event when a server gets boosted

vapid parcel
#

I need the docs for how it detects a boost :/

sick birch
#

just note that the .type attribute has to be MessageType.premium_guild_subscription

#
@bot.listen("on_message")
async def on_boost(message: discord.Message):
  if message.type != MessageType.premium_guild_subscription:
    return
  
  print(f"{message.author} just boosted {message.guild}!")
vapid parcel
#

Okay, ty

final iron
#

I don’t see why it needs to be awaited

#

It looks like a list

patent lark
#

so ive gotten myself in a bit of a rut here.

Im trying to disable commands per-guild IF the guild has not been configured. My idea was to use before_invoke and stop the command from completing there. I just cant seem to stop the command from executing though. Any ideas?

stark nexus
# final iron What is initial_extensions

Adding Cogs to your Discord Bot is one of the best things you can do. It transforms your Discord Bot and Python code into something that is undoubtedly better via the use of Cogs.

It allows for all of your commands and events to be organised into corresponding sections which means that it's a lot easier to read and understand the Python code f...

▶ Play video
final iron
#

Or you could just answer my question…

patent lark
naive briar
patent lark
naive briar
#

You can override the on_message event to only process the commands from the guild messages if it's in a list or whatever you're using to configure it

patent lark
#

Thank you

naive briar
#

🐈

glad cradle
spark nimbus
#

hey i am trying to do cogs but i cant really make it work
this is my main code:

import settings
from settings import *
import discord
from discord.ext import commands
from discord import app_commands
import os
import string
import random
import asyncio


intents = discord.Intents.all()
intents.messages = True
intents.message_content = True
client = commands.Bot(command_prefix='.', intents=intents)


@client.event
async def on_ready():
    print(f'{client.user.name} is running')
    try:
        synced = await client.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)
    client.remove_command("help")


for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')


client.run(BOTTOKEN) 

this is my command code:

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


class coin(commands.Cog):
  def __init__ (self, client):
    self.client = client

    @commands.command(name="coin", description="Flip a coin")
    async def coin(ctx, choice: str):
      choices = ["Heads", "Tails"]

      if choice not in choices:
        await ctx.send("Please choose either 'Heads' or 'Tails'.")

      result = random.choice(choices)

      embed = discord.Embed(title="Coin Flip", color=discord.Color.gold()),
      embed.add_field(name="Your Choice", value=choice, inline=False),
      embed.add_field(name="Result", value=result, inline=False)

      await ctx.send(embed=embed)


def sutup(client):
  client.add_cog(coin{client})
fading linden
#

useless ping sorry kek

slate swan
#

Pointless to set messages and message_content to true as well if you already have intents set to all()

spark nimbus
slate swan
#

And look at coin{client} again

spark nimbus
#

dont need help anymore

#

thanks

slate swan
#

And you should upgrade the library version, it's outdated

solar glen
#

since i can't change the actual webhook's image. il just create a brand new webhook and delete it per iteration

#

i think it might work

#

but its really inefficient

#

i just wish i could input the bytes instead

#

for changing and not creating and deleting

#

nvm

#

i found a function and its webhook.edit

vapid parcel
#

So, when a bot does botname is thinking... an its animated, do you have to have your bot verified for that? Or how do they make it animated n stuff?

#

For example for Mee6 it would be Mee6 is thinking...

golden portal
#

error doesnt match the code

fiery cairn
#

full error:

golden portal
#

error still doesnt match the code, did you make sure to save the code before running?

fiery cairn
#

yep defo saved

fiery cairn
golden portal
#

now it's updated

fiery cairn
#

alr

#

so do you know how to fix it?

golden portal
#

Member is Guild specific, so you may try typehinting to discord.User instead

#

oh nvm they translated to the same thing in slash

fiery cairn
#

??

golden portal
# fiery cairn ??

when you do user: discord.Member, you're trying to get a member that is in the guild which makes no sense because you're unbaning them, they are not in the guild

fiery cairn
#

oh ok

#

so I just remove discord.Member

#

and then do I just do /unban their id?

golden portal
fiery cairn
#

oh ok

golden portal
#

alright welcome

slate swan
#

yeah but in the on_approve def, i want it to add a role to the member that passed the application. To do that i didawait member.add_roles("Waiting for Interview")

#

but "member" isnt defined

#

you have defined it but its in another class

#

i tried to define it in the on_approve def as member = interaction.user but the bot think that member is the user that interacted with the approve message

golden portal
slate swan
#

ΟΗ

golden portal
#

essentially, ```py
role = discord.Object(ROLE_ID)
await self.member.add_roles(role)

slate swan
#

silly me

#

genius you

#

is this correct

#

?

naive briar
#

Try it

slate swan
#

ok

final iron
#

!d discord.Interaction.user

unkempt canyonBOT
fiery cairn
#

so interaction.user.roles?

#

worked thanks

slate swan
#

so the manager knows what he answered

#

to approve or to decline him

wispy pasture
#

Hi, so i found this code on github:
https://github.com/DorianAarno/Minesweeper-Discord-Bot/tree/main
and i tried to update and change to code from disnake == 2.3.2 to discord.py, and if you have helped me before and remember me then you know it went very very bad.... so my code and error is in the sourebin down below:
https://sourceb.in/7q7c2LEnde (code)
https://sourceb.in/D7fq0NU7vR (error)

GitHub

Play interactive minesweeper with button components within discord! - GitHub - DorianAarno/Minesweeper-Discord-Bot: Play interactive minesweeper with button components within discord!

naive briar
#

I dislike the naming already 🫠

wispy pasture
#

ps i told clearly thats not my code 😂

harsh orbit
#

is httpx has blocking on discord.py like requests?

glad cradle
#

well

#

interaction.response is a discord.InteractionResponse object

#

and interaction.command is an app command object

fiery cairn
#

ok

glad cradle
#

you need to access their attributes to get useful info for logging

fiery cairn
#

so I can't run it in an embed

#

!d

glad cradle
#

!d discord.InteractionResponse

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response).

New in version 2.0.
fiery cairn
#

Thank u

glad cradle
glad cradle
#

!d discord.app_commands.AppCommand.name

unkempt canyonBOT
fiery cairn
#

thanks

glad cradle
#

to get the name of the command

#

you can check the docs for these things

#

here there are all the available public attributes for the objects

fiery cairn
#

But so how do I also send the output?

glad cradle
#

wdym? the output of the command?

fiery cairn
#

Like to get also send in the logs what the command output was

#

nvm

wispy pasture
#

Hi, so i found this code on github:
https://github.com/DorianAarno/Minesweeper-Discord-Bot/tree/main
and i tried to update and change to code from disnake == 2.3.2 to discord.py, and if you have helped me before and remember me then you know it went very very bad.... so my code and error is in the sourebin down below:

#error
STARTUP /home/container: ${STARTUP_COMMAND} 
  File "/home/container/temp.py", line 1087
    def __init__(self, ctx, custom_id, label="", bombs, board):
                                                 ^^^^^
SyntaxError: non-default argument follows default argument```

code:
https://srcb.in/mAFDbrTA4Q
GitHub

Play interactive minesweeper with button components within discord! - GitHub - DorianAarno/Minesweeper-Discord-Bot: Play interactive minesweeper with button components within discord!

naive briar
#

!e read the error

# valid
def a(arg_one, arg_two): ...

# valid
def b(arg_one, arg_two=""): ...

# invalid
def c(arg_one="", arg_two): ...
unkempt canyonBOT
#

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

001 |   File "/home/main.py", line 8
002 |     def c(arg_one="", arg_two): ...
003 |                       ^^^^^^^
004 | SyntaxError: parameter without a default follows parameter with a default
wispy pasture
naive briar
#

Explain you? lemon_raised_eyebrow

shrewd fjord
#

tbh i dont know why add this restriction pithink

shrewd vapor
#

Hiii

#
2023-10-25 16:29:29 ERROR    discord.client Ignoring exception in on_member_update
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/main.py", line 392, in on_member_update
    cursor.close()
  File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/cursor_cext.py", line 495, in close
    self._cnx.handle_unread_result()
  File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/connection_cext.py", line 961, in handle_unread_result
    raise InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found```
#
@bot.event
async def on_member_update(before, after):
    guild_id = before.guild.id
    connection = mysql.connector.connect(host = '', database = '', user = '', password = '')
    cursor = connection.cursor()
    query = "SELECT channel_id FROM log_moderation WHERE guild_id = %s;"
    cursor.execute(query, (guild_id,))
    row = cursor.fetchone()
    cursor.close()
    connection.close()
    if row is None:
        return
    channel_id = row[0]
    channel_send = before.guild.get_channel(channel_id)
    if len(before.roles) < len(after.roles):
        newRole = next(role for role in after.roles if role not in before.roles)
        if before.roles != after.roles:
            embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
            embed.add_field(name = "Role added :", value = newRole.mention, inline=False)
            embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
            await channel_send.send(embed=embed)
    elif len(before.roles) > len(after.roles):
        oldRole = next(role for role in before.roles if role not in after.roles)
        if before.roles != after.roles:
            embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
            embed.add_field(name = "Role removed :", value = oldRole.mention, inline=False)
            embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
            await channel_send.send(embed=embed)```
#

Can you help me please, i have never get this error before and i don't see any error here

naive briar
#

Swap the positions of the button and interaction parameters in your button callback

fiery cairn
#

Ok

#

Thanks

shrewd fjord
#

what confusing? hmm

naive briar
#

What if you want to set c without setting b first?

def a(\, b=0, c): ...
shrewd fjord
#

i mean now the args are positional only it makes sense here

#

but what about nothing, no * or no /

#

wait its a back slash RH_ieonn_se_pareshan

naive briar
#

Since then there will be no restrictions on how the caller provides the arguments

#

It's probably get confusing for the interpreter

#

*It'd

shrewd fjord
#

hmm, fair

naive briar
#

Sure ducky_drawing

white citrus
#

why is that crossed out?

final iron
white citrus
final iron
#

Also what does this have to do with discord-bots

white citrus
final iron
white citrus
final iron
#

Other and Web Development probably

vague junco
#
    @hybrid_command(name="announce", description="Отправить объявление от имени бота в указанный канал.", with_app_command=True, help="Отправить объявление.", nsfw=False, hidden=False, brief="Объявление.", usage="!announce <канал> <объявление>", guild_only=False, enabled=True)
    @commands.has_permissions(manage_messages=True)
    async def _announce(self, ctx: commands.Context, channel: discord.TextChannel, *,  message: str) -> Message:
        """
        Отправить объявление от имени бота в указанный канал.

        Parameters:
            ctx (commands.Context): The context of the command.
            channel (discord.TextChannel): Канал, куда отправить объявление.
            message (str): Сообщение, которое нужно отправить объявлением.

        Returns:
            discord.Message: The message sent by the bot indicating the result of the operation.

        Raises:
            Exception: If an error occurs during the execution of the command.
            discord.HTTPException: If an HTTP-related error occurs during the execution of the command.
            commands.MissingPermissions: If the bot is missing permissions required to execute the command.
        """
        try:
            if channel is None or channel not in ctx.guild.channels:
                return await ctx.send(embed=discord.Embed(description="Укажите канал, куда отправить объявление!", color=discord.Color.red()))

            if message is None:
                return await ctx.send(embed=discord.Embed(description="Укажите сообщение, которое отправить объявлением!", color=discord.Color.red()))

            embed = discord.Embed(title="Объявление", description=f"{message}", color=discord.Color.green())
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)

            await ctx.send(embed=discord.Embed(description="Объявление отправлено!", color=discord.Color.green()),ephemeral=False)
            return await channel.send(embed=embed)

        except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
            return await issue_msg(e, ctx)  # Handle any exceptions that occur during the execution of the command

how to handle the fact that the user does not specify anything in the chanel and message arguments when using the !announce command (not /announce)

slate swan
#

Set a default value to None, or ask the AI you've already asked

vague junco
#

And what makes you think I stole the code?

slate swan
#

It's fairly obvious.

Anyways, you can check the value these parameters have if you don't provide them in prefix commands, and then compare these in the future

#

damn, that's a new one

#

how to make a discord bot 101 2023 no fake 100% working

vague junco
slate swan
#

That's just the average teenager

#

Give them some time

final iron
#

What's the error

#

No

#

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

vague junco
#

No module named 'bot'

final iron
#

What is bot

#

What are you trying to import

#

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

vague junco
#

```py
```

final iron
#

This still doesn't answer the question

#

What is bot

#

No?

#

This literally doesn't answer my question

#

What is bot. Is it a local file, module etc

vague junco
#

just replace your token in this file, and run through it...?

final iron
#

Could you show your file structure?

#

No

#

Shift + windows key + s

#

It'll be saved to clipboard and you can paste it in

#

???

vague junco
#
import discord

TOKEN = ''
bot = discord.Client(commnds_prefix='!', intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f'{bot.user} is now running!')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    username = str(message.author)
    user_message = str(message.content)
    channel = str(message.channel)

    print(f"{username} said: '{user_message}' ({channel})")

bot.run(TOKEN)
#

lol

slate swan
#

How to make bot 101

a. Enable all intents, very important
b. Make sure to name your bot variable client, and alternatively your client variable bot

vague junco
#

ahhaha

#

🤓

slate swan
#

Oh and
c. Make sure to str() everything, and then use f-strings so that it's done twice

vague junco
#

simply

final iron
vapid parcel
final iron
# vapid parcel Why?

Why would discord restrict thinking events to verified bots only? A user typing isn't really a privileged event

vapid parcel
#

It was a question..?

#

Idk why you gotta be a dick abt it..?

final iron
#

I'm not...

#

It's literally an explanation...

vapid parcel
#

Yeah, you say that but it's kinda a yes or no question, then explain how to do it, but you avoid what I'm asking... just wanted to know if it needs to be verified and how to do it..

glad cradle
final iron
#

And you've already been told how to do it in the discord.py server

#

So I didn't see the need to repeat it

glad cradle
#

!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...
vapid parcel
#

I do both servers to make sure..?

final iron
vapid parcel
#

Cuz sometimes they give a different point of view that's why..?

#

Or explain it differently.

final iron
#

I mean the docs explain it all

#

And I don't see why there would be a different point of view as it's just True/False being passed to a kwarg

#

There really isn't any other way to do it

vapid parcel
#

I mean I've gotten 2 different point of views multiple times

final iron
#

This is literally the only solution

vapid parcel
#

Yeah, but I didn't know that, I wanted to make sure 😭

final iron
#

Sure, but there's absolutely 0 reason to call me a dick

vapid parcel
#

I already explained why..

vapid parcel
#

From my pov it just seems like you were being a dick, sorry I called you a dick, but from my pov it just looks like you were.

final iron
#

You asked a question, I answered and then clarified

vapid parcel
#

I'm talking abt before :/

#

Like I said, I'm sorry, but from my pov it just seems like you were trying to be a dick.

final iron
#

And that was wrong

#

Just avoid calling people dicks in the future, for any reason really

vapid parcel
#

I mean I could say worse 😭😭

#

But I have no reason, and no one should tbh, but like I said, I am sorry for calling you a dick.

next heath
#

Hi im having trouble whit a leave longing system. When i leave the server the on_member_removed event docent respond to the event
Code:

def add_score(member: discord.Member, amount: int):
    if os.path.isfile("./data/Leave.json"):
        with open("./data/Leave.json", "r") as fp:
            data = json.load(fp)
        try:
            data[f"{member.id}"]["score"] += amount
        except KeyError: 
            data[f"{member.id}"] = {"score": amount} 
    else:
        data = {f"{member.id}": {"score": amount}}
    with open("./data/Leave.json", "w+") as fp:
        json.dump(data, fp, sort_keys=True, indent=4)

def get_score(member: discord.Member):
    with open("./data/Leave.json", "r") as fp:
        data = json.load(fp)
    return data.get(f"{member.id}", {}).get("score", 0)

def in_channel(*channels):
    def predicate(ctx):
        return ctx.channel.id in channels
    return commands.check(predicate)

@client.event
async def on_member_leave(member):
    await add_score(member, 1)
    print("Leave")
final iron
next heath
#

oh is on_member_removed then?

slate swan
#

Nope

#

!d discord.on_member_remove

unkempt canyonBOT
#

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) leaves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

If the guild or member could not be found in the internal cache this event will not be called, you may use [`on_raw_member_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_member_remove) instead.

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

Search feature is pretty useful

next heath
#

Tnx

young dagger
#

How can you prevent users from spamming others DM on your Discord server?

tender bobcat
#

if there are, just turn off dm for 12 hours

#

*if there are a lot

final iron
#

Is that even available for bots

tender bobcat
#

i dont think so

final iron
#

So…

tender bobcat
#

but I don't think anything else can prevent spam dm

final iron
#

This is discord bot channel. It’s pretty obvious he wants a programmatic solution

tender bobcat
#

how do you programmatically prevent spam dm when the bot don't even know there are dm

final iron
#

It’s not possible

tender bobcat
#

yeah exactly, so I tell him the only possible solution

final iron
#

The whole point of having a bot is to automate tasks

#

Manually doing something like this, especially if it’s a security bot isn’t feasible

tender bobcat
#

except discord doesn't make an API for it, how terrifying

final iron
#

Yeah, so it’s not possible

tender bobcat
#

yeah, not possible with bot

final iron
#

That’s the whole point

tender bobcat
#

and seriously discord should do better at this

#

at least make an API, it is not that hard

final iron
#

There's currently a lot of features missing from the bot API

tender bobcat
#

yeah

final iron
#

Considering bots were, and still are the backbone of discord's ecosystem I don't understand why

tender bobcat
#

like when start typing is an event call, why not stop typing is an event call as well

final iron
#

Up until around 2 years ago it was extremely difficult to moderate exclusively through discord

#

Impossible for large servers

#

If there was raid and you didn't have a bot, then you would have to close the entire server manually

#

If you weren't there to do it you were SOL

tender bobcat
#

like when you try to make it easier for human to moderate, why not make bot easier as well

#

bot is way more effective

final iron
#

Yeah

#

It's getting better than it was, but it still sucks

edgy plinth
#

I'm trying to iterate through all the server roles in a command to appear as options.

Ive been stuck on this for a good time now, any solutions?

tender bobcat
#

yeah, literally if you marked flag on user on suspicious dm event, why cannot bot know it and do action automatically

tender bobcat
tender bobcat
#

and it will have all the role listed

final iron
tender bobcat
#

in discord way

final iron
#

https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type
These types can be translated to Python or discord.py types and used as typehints for slash commands.
STRING ->
- str
- app_commands.Range[str, min_length, max_length]
INTEGER -> does not support IDs
- int
- app_commands.Range[int, min_value, max_value]
BOOLEAN -> bool
USER -> in a guild, you will receive a member regardless of typehint, but it will not have presence data
- discord.User
- discord.Member
- Union[discord.Member, discord.User]
CHANNEL -> Union containing any number of these types is supported
- discord.Thread
- discord.abc.GuildChannel - all below
- discord.CategoryChannel
- discord.ForumChannel
- discord.StageChannel
- discord.VoiceChannel
- discord.TextChannel - text, news
ROLE -> discord.Role
MENTIONABLE -> Union with any combination of USER and ROLE
NUMBER ->
- float
- app_commands.Range[float, min_value, max_value]
ATTACHMENT -> discord.Attachment

Notes:

final iron
final iron
#

Yes you can

#

Show how you did it

#

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

tender bobcat
#

role: discord.Role

#

and you don't need choice

edgy plinth
patent lark
#

@final iron are you good with working with mongo DB?

final iron
#

Nah

#

Never touched it

#

I use sqlite3

patent lark
#

ah alright

slate swan
grand bobcat
#

is discord.py easier then discord js? I have more experience in python

final iron
sick birch
wispy pasture
shrewd fjord
# wispy pasture Hi, so i found this code on github: https://github.com/DorianAarno/Minesweeper-D...
    async def callback(self, inter):
        assert self.view is not None
        view = self.view
        await inter.response.defer()
        if inter.user.id != self.ctx.author.id:
            return await inter.send("You cannot interact with these buttons.", ephemeral=True)

        b_id = self.custom_id
        if int(b_id[5:]) in view.moves:
            return await inter.send("That part is already taken.", ephemeral=True)
        if int(b_id[5:]) in self.bombs:
            await view.RevealBombs(b_id, view.board)

first of all if you are using discord.py there's no .send in Interaction iirc instead use
await inter.followup.send(...)

#
            if len(view.moves) + len(self.bombs) == 25:
                await inter.response.edit_message(view=view)

                await view.EndGame()

        await inter.response.edit_message(view=view)

you have already responded with the interaction using defer, to edit the message again consider using
await inter.edit_original_response(....)

#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
bitter tundra
#

how do I make a button view that never expires

slate swan
#

It expires when you restart the bot

bitter tundra
slate swan
#

Idk if that's possible

#

Bot restarts = buttons restart

shrewd fjord
#

!d discord.Client.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
shrewd fjord
#

then use this to add the persistent view when bot starts

#

and for making a view persistent, you must pass timeout=None in the view and set a custom_id for every childrens in the view

bitter tundra
#

So I am specifying the userid on the custom_id when I create the view like this quit:userid where I want to check if the user's id who clicked the the button is same as userid, how do I implement this in presistent view?

vocal rivet
#

Is there a way to connect 2 clients in a single script?

naive briar
#

Yes

vocal rivet
naive briar
#

Use asyncio's tasks system to start the clients by their client.start method

#

Either by asyncio.TaskGroup (python >= 3.11) or asyncio.gather or even manually creating and awaiting the tasks

naive briar
#

!d asyncio.TaskGroup take a look

unkempt canyonBOT
#

class asyncio.TaskGroup```
An [asynchronous context manager](https://docs.python.org/3/reference/datamodel.html#async-context-managers) holding a group of tasks. Tasks can be added to the group using [`create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task). All tasks are awaited when the context manager exits.

New in version 3.11.
slate swan
#

how do i make my discord bot automatically send a message as soon as a ticket is made by ticket tool

vocal rivet
#
async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(client.run(token1))
        task2 = tg.create_task(client.run(token2))```
#

Any idea why this isn't working?

trail helm
#

Does anyone know how to make my discord bot responsive?

vocal rivet
trail helm
vocal rivet
#

Is that what you meant ?

trail helm
#

Yes, thanks

vocal rivet
#

Np, btw you'll need to add another line of code if you want your bot commands to function:

@bot.event
async def on_message(msg):
  await msg.reply("Hello World")
  
  await bot.process_commands(msg)
slate swan
#

how do i make my discord bot automatically send a message as soon as a ticket is made by ticket tool

naive briar
#

@vocal rivet That's because the client.run is just a normal, not a coroutine (not awaitable basically). I told you to use the client.start that is awaitable

#

!d discord.Client.start

unkempt canyonBOT
#

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

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect).
vocal rivet
#

Oo ok

vocal rivet
#

@naive briar

naive briar
#

What?

vocal rivet
naive briar
#

You're not even running the main function you defined

vocal rivet
#

Oh shit

#

Should I call it at the end of the script?

naive briar
#

Yes?

winter token
#

what's the decorater to mark a discord bot cmd as owners only cmd

vocal rivet
#

RuntimeError('Event loop is closed')

naive briar
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

dry oak
winter token
dry oak
#

bro.....

#

Has got nothing to do with not wanting to help, you didn't even try....

slate swan
unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner).

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner) that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
slate swan
lyric sigil
#

Do someone know how can i make a uptime command ?

lunar vector
#

.

slate swan
#

Save the time in a bot variable when the bot started

#

In the command get the difference between the time now and the saved start-up time

shrewd fjord
brazen raft
naive briar
#

!d time.monotonic more like

unkempt canyonBOT
#

time.monotonic() → float```
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.

Use [`monotonic_ns()`](https://docs.python.org/3/library/time.html#time.monotonic_ns) to avoid the precision loss caused by the [`float`](https://docs.python.org/3/library/functions.html#float) type.

New in version 3.3.

Changed in version 3.5: The function is now always available and always system-wide.

Changed in version 3.10: On macOS, the function is now system-wide.
wispy pasture
#

hey people.... one thing is
followup.send

but i want to edit my message.... what was the followup for edit?

slate swan
#

someone tell me how to make buttons work even after restarting the bot?

wispy pasture
slate swan
#

i have a lot of buttons

wispy pasture
# slate swan i have a lot of buttons

welll.... until what i know, thats the way.... or a big shot might or might not work:
add all the buttons in 1 class view (again i might be saying the wrong function name) and add that class view in the bot ready event

stark nexus
#

Anyone can help me with this?

@client.tree.command(description='Random decide team')  
async def r_player(interaction: discord.Interaction, player1: str, player2: str, player3: str, player4: str, player5: str, player6: str, player7: str, player8: str, player9: str, player10: str):
    
    players = [{player1}, {player2}, {player3}, {player4}, {player5}, {player6}, {player7}, {player8}, {player9}, {player10}]

    random.shuffle(players)  
    
    Bravo = [players[0], players[1], players[2], players[3]]
    Alpha = [players[4], players[5], players[6], players [7]]
    Charlie = [players[8], players[9]]
    
    
    embed = discord.Embed(title="Random Player picker(Private battle)", description= "Allow you to random decide team members")
    
    embed.add_field(name="Team Alpha", value=Alpha)

    embed.add_field(name="Team Bravo", value=Bravo)
    
    embed.add_field(name="Team Spectator", value=Charlie)
    embed.set_image(url="https://media.discordapp.net/attachments/971919486934478858/1167097215785906228/Private-Battle.jpg?ex=654ce2fb&is=653a6dfb&hm=01c0c477e30d8e7320a1edcecd24a41ee1bf03cd8a48e8efa374cfbd441e844d&")
    
    await interaction.response.send_message(embed=embed)```
burnt idol
#

is there any way i can select which buttons to display on first line( or does discord chooses that by itself)
like i want to be able to show 1 button on line 1 then 2 buttons below it!

bitter tundra
#

In persistent view how do I check if the user who clicked the button is same as the user who ran the command?

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
shrewd apex
#

row=

velvet tinsel
#

any recommended Bot hosting sites?

slate swan
robust fulcrum
velvet tinsel
robust fulcrum
#

wdym?

slate swan
#

alright listen up. I am attempting to build my own bot, I have decently good experience in coding in python so i want to use that, i boot up servral tutourials to see its all generally the same method Install Discord.py. ...
Create a Discord Application and Bot. ...
Create a Discord Guild (Server) ...
Add the Bot into the Server. ...
Code the Bot.

#

simple

#

so i boot up visual studio code (python ver. 3.11.6) and get to work

#

problem

#

its not connecting to the bot

naive briar
#

Are you running the bot instance?

velvet tinsel
# robust fulcrum wdym?

its just another way of saying "Okay."

And also - how would I time a command? Like, let's say I have

async def foo(ctx):
  timer.start()
  # some command here...
  timer.end()
  await ctx.send(some_result_here + "(executed in %s seconds)" % timer)
velvet tinsel
slate swan
#

im good but not that good, so i have no clue what this means

final iron
velvet tinsel
final iron
naive briar
#

@velvet tinsel How would I time a command?
Use the time.perf_counter or time.monotonic, for example:

import time

start_time = time.perf_counter() the
# do something
print(time.perf_counter() - start_time) # print the elasped time
final iron
naive briar
#

I can't edit or reply to messages, so you know

velvet tinsel
naive briar
#

Average Discord alpha bug

final iron
velvet tinsel
slate swan
slate swan
#

like the bot wont go online

naive briar
#

@velvet tinsel probably

final iron
#

Doesn’t answer the question

naive briar
#

I'd opt-out from it at some point

slate swan
#

[SSL: CERTIFICATE_VERIFY_FAILED]

#

this one

velvet tinsel
naive briar
#

New layout, I know that

#

And I hate it

turbid condor
velvet tinsel
naive briar
#

Why? pithink

#

I used that method many times to time my scripts

#

The edit button is back! ducky_sphere

brazen raft
#

It was caused by something else

velvet tinsel
brazen raft
#

Using time.monotonic won't fix your problem

brazen raft
slate swan
brazen raft
final iron
brazen raft
final iron
#

It’s not a module…

brazen raft
#

Well, is that file part of the package for use?

#

Could be cool to have

final iron
#

No?

slate swan
slate swan
brazen raft
slate swan
#

Fix?

slate swan
#

Cause I’m not exactly fluent in connective Wi-Fi terminology

#

Or https for that matter

brazen raft
#

To begin diagnosing, have you downloaded any other packages besides discord.py using pip? It should be the only package you need to develop Discord clients/bots in discord.py

#

Many tutorials out there are outdated and use forks or alternative packages for features the current version of discord.py now has

slate swan
#

I don’t remember installing anything else

brazen raft
#

Are you using any other networking module?

#

I know discord.py uses aiohttp under the hood, so are you using aiohttp for other uses?

slate swan
#

You know it might just be that

brazen raft
#

Using aiohttp isn't a problem in itself

slate swan
#

I’m gonna go check rq

brazen raft
#

Using aiohttp to communicate over HTTPS and providing a problematic SSLContext is more like the problem you're having

#

You always need to provide a valid context for that purpose

#

No matter whether it is aiohttp or any other Python tool which does that

hushed galleon
# slate swan [SSL: CERTIFICATE_VERIFY_FAILED]

a full error message would be more useful, but if you happen to be on macos and the error message looks like "unable to get local issuer certificate", here's a tag commonly sent in the discord.py server:

Getting [SSL: CERTIFICATE_VERIFY_FAILED] on Python 3 on OS X?
Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Happy coding!

hushed galleon
brazen raft
final iron
slate swan
# hushed galleon a full error message would be more useful, but if you happen to be on macos and ...

alright, File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection
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:1006)')]"

hushed galleon
#

yup, but i would recommend against attempting to handle message components manially

brazen raft
final iron
#

You could store all the views in a sequence and loop over it, but you eventually would have to add it as a view

brazen raft
hushed galleon
slate swan
#

right

hushed galleon
brazen raft
#

Then a handling system which sits on top of it for updating specifically

final iron
#

I don’t see why using an event is easier. It’s more messy, and it doesn’t really make sense

#

Callbacks are so much easier to work with

slate swan
#

IT WORKED

#

HAHAH

#

(happy tapdance)

#

@hushed galleon @brazen raft thanks guys

brazen raft
hushed galleon
slate swan
#

its always the most simple of fixes that get me

#

anyways

#

BACK TO THE VOID!

brazen raft
brazen raft
#

Oh it needs to be explicitly enabled for Python on that OS

hushed galleon
shrewd fjord
#

but you have to pass a particular custom_id in order to make the view and its components persistent

brazen raft
velvet tinsel
#

theres no fucking way im having difficulty with JSON files

brazen raft
brazen raft
#

My bad

#

That's off-topic

final iron
slate swan
brazen raft
#

In any case, this just means discord.py doesn't provide something like a PersistentView class to handle view changes neatly

#

for persistent views

#

Is there a setup_hook equivalent method for views?

#

Oh, I guess __init__ or something

#

Nah, that isn't called on add_view

#

Something that's called by add_view

hushed galleon
#

Are custom IDs a concept of discord.py?
basically as part of discord's API, every component must have a custom ID which discord sends to your bot so you know which component on a message was used
https://discord.com/developers/docs/interactions/message-components#custom-id

What does client.add_view to keep a view persistent?
internally, discord.py manages a mapping of component callbacks
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ui/view.py#L531-L532
when you send a message, all the view's callbacks are registered with your client so the next time it receives an interaction, it can lookup the corresponding callback
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/abc.py#L1564-L1565
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/state.py#L741-L746
client.add_view() simply registers those callbacks in the same way:
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/client.py#L2716

Does it implicitly trust the message provided by message_id to "keep the components state as last time" for the purposes of "using the same view after restart"?
yes, if you change a component's custom ID externally from your client object, dpy won't be able to lookup the correct callback
although in theory the exact parameters of those components don't have to be the same, i.e. if you were to change a button's style or throw away a few options from a select menu but you don't change their custom ID, dpy can still dispatch the view afterwards

In any case, this just means discord.py doesn't provide something like a PersistentView class to handle view changes neatly
i don't see why they need to? only your bot can edit the components so it shouldn't expect them to change out of its control

brazen raft
#

Oh I skipped over the first line about message components in the developer portal. My bad

#

Or, I guess, good learning for me

#

I thought they were something like message attachments which could be edited by other applications

#

Actually is even that possible

#

🤔

#

Possible. In any case, good to know

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 497, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 97, in on_ready
    if not persistent_view_added:
UnboundLocalError: local variable 'persistent_view_added' referenced before assignment
#
def main():
    bot = commands.Bot(intents=nextcord.Intents.all(), help_command=None, case_insensitive=True)
    

    load_dotenv()
    
    secret_file = json.load(open(cwd+'/bot_config/secrets.json'))
    bot.config_token = secret_file["token"]

    bot.cwd = cwd

    ipc = Server(bot=bot, secret_key="lol")
    
    StartUpDB()
##################################################################################################################################################################  
    
    # load all cogs
    for folder in os.listdir(os.getcwd() + "/modules"):
        if os.path.exists(os.path.join(os.getcwd() + "/modules", folder, "cog.py")):
            bot.load_extension(f"modules.{folder}.cog")
            
    # load detections
    for folder in os.listdir(os.getcwd() + "/cogs"):
        if os.path.exists(os.path.join(os.getcwd() + "/cogs", folder, "ghost_ping.py")):
            bot.load_extension(f"cogs.{folder}.ghost_ping")
    
##################################################################################################################################################################
        
    @Server.route()
    async def guild_count(self, _):
        return str(len(self.guilds))
    

    @Server.route()
    async def bot_guilds(self, _):
        guild_ids = [str(guild.id) for guild in self.guilds]
        return {"data": guild_ids}


    @Server.route()
    async def guild_stats(self, data: ClientPayload):
        guild = self.get_guild(data.guild_id)
        if not guild:
            return {
                "member_count": "Unbekannt",
                "name": "Unbekannt"
            }
        
        return {
            "member_count": guild.member_count,
            "name": guild.name,
        }


    async def on_ipc_error(self, endpoint: str, exc: Exception) -> None:
        raise exc  
    #########################################################################
    persistent_view_added = False

    @bot.event
    async def on_ready():

        if not persistent_view_added:
            bot.add_view(TicketMain_One)
            bot.add_view(TicketMain_Two)
            bot.add_view(TicketMain_Three)
            persistent_view_added = True```
brazen raft
#

Are the line with persistent_view_added = False and the line with async def on_ready(): in the same file?

hushed galleon
brazen raft
# hushed galleon users can delete attachments from someone else's messages? i havent noticed that...

To remove or replace files you will have to supply the attachments field which specifies the files to retain on the message after edit.
from: https://discord.com/developers/docs/resources/channel#edit-message

Discord Developer Portal

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

brazen raft
brazen raft
white citrus
brazen raft
#

Are they both under that main function directly?

#

Not inside some sort of an inner function

white citrus
brazen raft
#

It won't raise that exception if this is the case

hushed galleon
# white citrus ```Ignoring exception in on_ready Traceback (most recent call last): File "C:\...

because you have the assignment persistent_view_added = True in your on_ready function, python assumes persistent_view_added is a local variable, i.e. a variable that only exists in that function
in other words, python is ignoring your persistent_view_added = False declaration, hence why python thinks the variable isn't defined when it tries running if persistent_view_added:
in your case, you need a nonlocal declaration to tell python that it should refer to the variable in main() instead: py def main(): persistent_view_added = False def on_ready(): nonlocal persistent_view_added if persistent_view_added: # now python knows to use the definition in main persistent_view_added = True see also: https://docs.python.org/3/faq/programming.html#faq-unboundlocalerror

brazen raft
#

I'm gonna need to see the entire function definition

white citrus
brazen raft
#

Oh I didn't catch that

#

Um

white citrus
brazen raft
#

I didn't know Python's variable declaration worked like JavaScript's let

#

I thought it looks for the name in the local scope and then in outer scopes until it finds or raises a NameError exception

#

But I didn't know it firstly checks whether it is assigned later on in the local scope

hushed galleon
white citrus
#

How should I pass the arguments now? just with None?

#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 497, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 98, in on_ready
    bot.add_view(TicketMain_One())
TypeError: TicketMain_One.__init__() missing 7 required positional arguments: 'guild_id', 'header', 'textbox', 'button_one', 'f_re', 'channel', and 'category'```
brazen raft
hushed galleon
brazen raft
white citrus
hushed galleon
#

yup, thats the hard part

#

that's usually where a database comes in, so you can store whatever information is necessary to create your views with the same parameters as last time

brazen raft
#

Does your bot send tickets regarding different guilds and such, or does it suffice to get this information from the view's message?

white citrus
hushed galleon
brazen raft
hushed galleon
#

if it's not possible or it would be unnecessarily complicated, you should either remove parameters that you don't really need and/or store the parameters that you definitely need in your database

brazen raft
#

remove parameters that you don't really need
to know on construction

white citrus
brazen raft
white citrus
#

But i can change it

#

Gime a sec

brazen raft
# white citrus Is stored in a other table

If these are stored in the database, you need to query that info, too, to add the persistent view. The question is whether they can be fetched after constructing the view so you don't have to do that

mental hollow
#

how do I add roles to a user using role IDs

hushed galleon
#

Member.add_roles() accepts any snowflake, so discord.Object(1234) would be how you'd add a role to them with only the ID
(although usually you can use Guild.get_role() too if your bot's cache is ready and you have the guilds intent enabled)

mental hollow
#

thank youu

hushed galleon
#

*roles denotes a variadic parameter, meaning it can take any number of arguments

mental hollow
#

await member.add_roles([discord.Object(123), discord.Object(456)]) would that work

hushed galleon
white citrus
brazen raft
slate parrot
#

anyone know why this is happening?

#

why was my code deleted

#

or error lol

#
  self._run_job(job)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
final iron
#

Share your code

#

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

slate parrot
# final iron Something wasn't awaited

i have code where i try to make my bot stay online by sending a message every thirty seconds and i think thats the issue

# staying online
async def stay_online():
    staying_online = bot.fetch_channel(1166153894666186892)
    try:
        await staying_online.send("Staying online!")
    except:
        pass
        
schedule.every(30).seconds.do(stay_online)

while True:
    schedule.run_pending()
    time.sleep(30)```
#

OOOPS i think i found the issue

#

nvm

brazen raft
slate parrot
#

and i dont want it to go offline so it bothers me

#

and im trying to program something else

#

that uses the schedule package

#

so the bot needs to be online for it to work

brazen raft
#

You can take a look at Replit's template for a discord.py bot with a "keep alive" mechanism

#

It or something like it may work on your hosting server

slate parrot
brazen raft
#

I recommend setting your hosting server to not go offline every thirty seconds to begin with

slate parrot
brazen raft
slate parrot
#

idk why its happening to me then ¯_(ツ)_/¯

brazen raft
#

An output like "client reconnecting in 700 seconds" could only be logged by the program

#

If not by the program, who else knows you're running a client program?

slate parrot
#

thats not exactly whayt it says its like

#

"discord.client" with a big red "ERROR" next to it and it says that

#

the "ERROR" is to the left of it

#

and their servers are pterodactyl servers

brazen raft
slate parrot
#

yeah and it gives me warnings saying something about webhooks or sockets or wtv?

brazen raft
#

The only time I can think when this may happen is when the internet connection is problematic enough to cause disconnection

final iron
brazen raft
#

The other reason for being terrible is causing an unstable connection to Discord

#

If my suspicions are correct

slate parrot
#

what host should i use then

slate parrot
brazen raft
#

Hosts with a shared IP address, as the name suggests, share an IP address for multiple hosted environments. You end up with the same IP address as other users, so if anyone makes the IP address be banned from connecting to a server, all of you will be banned from it

#

Usually, there's nothing you can do about it

slate parrot
#

wait so ur saying if someone ddoses the ip then my bot and everyone else with that ips bots will fail

brazen raft
slate parrot
#

😐

#

what good bot host should i use cause i dont always leave my computer on

brazen raft
#

Well, I don't think communication using just the IP is denied. I think it's a combination of the IP + the port for your program, which is unique to you and isn't used by others

slate parrot
#

cause i want a free bot host that works

brazen raft
brazen raft
#

If it's not your personal computer, it's someone else's

slate parrot
#

does this work

final iron
#

Why can't you just buy a normal VPS

brazen raft
#

It says "try for free"

#

I'm assuming it's a well-respected service

#

Unless it's a free trial which lasts forever

brazen raft
slate parrot
brazen raft
#

Then you have to live with what you've got

final iron
#

These "Discord Bot Hosting Sites" are generally more expensive than normal hosting services

slate parrot
slate parrot
#

im debugging it in vs code 2022

#

17.7.6

brazen raft
#
from discord.ext import tasks

@tasks.loop(seconds=30)
async def keep_alive():
    channel = bot.get_channel(1166153894666186892)
    await channel.send("Staying online!")

Then, you need to start the task via keep_alive.start() on startup

#

or whenever you care to

#

It loops automatically every 30 seconds

slate parrot
#

so do i put in the keep alive function keep_alive.start()?

#

or do i do it like how i did the schedule.run stuff

brazen raft
brazen raft
#

You need to manage startup functions in bot.setup_hook

slate parrot
#

can u show me how im a bit confused (im not a professional that much on python)

brazen raft
#

In your case, it's a matter of reassigning bot.setup_hook to an async def function

#
async def on_startup(self):
    keep_alive.start()

bot.setup_hook = on_startup
bot.run(...)
slate parrot
#

can i put this on a on_ready function

brazen raft
#

You shouldn't run startup logic in that function

#

It's not its intended purpose

#

on_ready may be called an unexpected number of times, including never, once or more

slate parrot
brazen raft
#

You reassign bot.setup_hook with an async def function which accepts the bot as the first argument. That async def function performs startup logic, which as far as I know, in your case, calls keep_alive.start()

#

That should get the loop going

#

It won't stop your connection to Discord from turning unstable though

#

So it's unnecessary to begin with

brazen raft
slate parrot
brazen raft
#

Discord applications rely on a stable connection to Discord. If that's out of the question because of the hosting service, use a different one

#

Under normal circumstances, you don't need a "keep alive" mechanism

slate parrot
#

and i got the cheapest plan

#

and it uses 20 percent cpu max 😅

brazen raft
#

Test Autocode without a "keep alive" mechanism

#

That's when you know it has suitable connectivity

slate parrot
#

ok thank you

brazen raft
#

You would get this from bad virtual private hosts

slate parrot
#

and i have the argument??

final iron
brazen raft
# slate parrot

Do you have bot.setup_hook = on_startup like I spoonfed you?

slate parrot
brazen raft
slate parrot
brazen raft
brazen raft
wicked atlas
#

setup_hook does not take any arguments

brazen raft
#

I didn't know it's a static method in discord.Client

#

I always subclass it so I can use it as a regular method

brazen raft
#

Make sure bot is never reassigned anywhere

slate parrot
#

how is it none

brazen raft
#

Replace bot.get with await bot.fetch

brazen raft
slate parrot
#

😎

#

my only problem is this now

#
# tells us client is ready
@bot.event
async def job():
    for guild in bot.guilds:
        print(f"We have logged into {guild} as {bot.user}")
        await console.send(f"We have logged into {guild} as {bot.user}!")```
#

oh wait bruh

brazen raft
#

You need to move this logic to on_startup

#

You might want to implement sending the message to console in an actual single message instead of many

#

Rate limits are a thing with Discord

slate parrot
#

i use ethernet too with 400 mgb

#

nothing wow

#

@brazen raft

final iron
#

This is some basic python

#

Your function doesn't return anything, and you never called it

brazen raft
#

I've been spoonfeeding him for this

#

@slate parrot It's time to take your time learning Python thoroughly before stumbling on things like this

slate parrot
#

bro ive been using python for about a year now

#

doesnt mean im gonna know everything 😒

final iron
#

Obviously not, but calling functions is some pretty basic stuff

brazen raft
#

This means you haven't learned basic Python for over a year now

#

You never want to rely on others to write code for you unless you pay them enough money

#

And paying money for work is against this server's rules

slate parrot
#

ok bro

slate parrot
#

i am not that experienced in python been working with python for a year now doesnt mean that ur spoonfeeding me everything if u tell me how to do something if im doing it wrong

brazen raft
#

I'm here to help with the project and I've already spoonfed you about using the library

#

I cut the line with spoonfeeding you about Python in general

#

Here are learning resources:

#

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

slate parrot
#

@brazen raft its been fifteen minutes and no socket interupptions or anything

#

wtv theyre called

#

so ye the code works

brazen raft
#

Good for you on finding a VPS with a stable connection to the internet

#

Although expensive

final iron
#

$19 for that host lol

#

Absolute scam honestly

#

You could probably get a 4 core VPS for like $12 a month

#

This one is dedicated

grand kettle
#

i prefer raspberry pis

slate swan
#

Anyone knows if there is a function like on boost event? And if yes can anyone make a quick example

slate swan
grand kettle
#

yeah it's fine
we all do that

slate parrot
brazen raft
#

It isn't the same host if the problem no longer occurs

slate parrot
desert kiln
#

hello people

slate parrot
#

im not using a differnet host at all its the same server same host

brazen raft
#

Then having an unstable internet connection inconsistently is a sign of unreliability

slate parrot
#

its not running off of my computer

desert kiln
#

I have no idea what's going on

brazen raft
#

Servers are typically highly specialized computers

#

Failing to work with the international network is a big fat L

#

Though not unheard of and there are cases where this isn't necessary. Not in this case though

slate parrot
# desert kiln I have no idea what's going on

basically i wanted code so that my discord bot could stay online cause if no commands are ran and it idles it goes offline and keeps trying to connect back to discord but it cant i use a terrible host

desert kiln
final iron
#

Considering their billing page doesn't even work due to a cloudflair issue I can't imagine it's a good host

#

Also this is like exceptionally bad

#

"free hosting" does not exist outside of free credits

#

Everything will be trash

#

I don't understand how you don't have the 4 euro a month to pay for an actually good VPS

desert kiln
final iron
#

Anecdotal

#

Just because you had a "nice" experience, doesn't mean everybody will

shrewd fjord
unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.

graceful haven
#

Hi i dont know why it does this

#

could someone help

harsh orbit
#

in on_member_join event
How to check what the guild that user joined to cuz the bot in mor than 1 server

robust fulcrum
graceful haven
robust fulcrum
#

And consider using powershell to run python, the python shell doesn't support colored output I guess

graceful haven
buoyant quail
#

Line 327. You are passing check=check but you don't have anything named check

buoyant quail
buoyant quail
#

Create that function and make there anything you need

graceful haven
#

im stupid

buoyant quail
#
def check(...):
   ...
graceful haven
buoyant quail
#

In your code. And it's example function because i can't know what you want to do inside.

robust fulcrum
#

This is the output of seeing a random discord bot making blog on Google 💀

#

Or not learning python first

buoyant quail
#

Surely second
But it can be combined with first :D

robust fulcrum
#

Tbh I daily see atleast such 4-5 people

#

I would recommend them to learn python properly and then they are open to make discord bots

graceful haven
#

when i try run it

robust fulcrum
#

If you wana create it , then open it with w mode

#

or r+

buoyant quail
#

It exists (i can see it in the left), but the path to it is incorrect i guess

#

The path to the file should be from the current working directory.

graceful haven
#

it works when i open it with python power shell

robust fulcrum
#

oops not seen , there are so many files lol

graceful haven
robust fulcrum
#

Btw which extension you using for seeing such error?

graceful haven
#

idk

robust fulcrum
#

Try correcting path

graceful haven
robust fulcrum
#

Or use pathlib

#

I mean file path

graceful haven
robust fulcrum
#

from which directory you running your code?

#

I mean working directory

graceful haven
robust fulcrum
#

Type it in terminal
pwd

#

And send me output

graceful haven
#

that

robust fulcrum
#

So you running from this directory , right?

graceful haven
#

yes

robust fulcrum
#

And config.json is in this dir? Or in any sub dir?

graceful haven
#

it is in that dir

buoyant quail
#

it's inside the Receipt Big Bot

robust fulcrum
#

Ok

graceful haven
robust fulcrum
#

i am confused i guess

graceful haven
#

its not even my bot

#

the owner discontinued the bot

robust fulcrum
#

Try running your code from receipt big bot folder

graceful haven
#

bc he couldnt be asked to pay for hosting

graceful haven
robust fulcrum
#

Bro learn some basic commands

#

Like
cd

#

just cd into that folder and run the main.py file

graceful haven
#

ok

#

how do i run

robust fulcrum
#

Do you know about running python files?

graceful haven
#

its been like 2 years since ive done anycoding

robust fulcrum
#

You should revise I guess

graceful haven
#

ye

robust fulcrum
#

Then try making bot

graceful haven
#

how do i run the file

mystic marsh
#

hmm

mystic marsh
graceful haven
mystic marsh
#

On vsc?

graceful haven
#

no

mystic marsh
#

where then

buoyant quail
#

python main.py
maybe py main.py

robust fulcrum
#

There is run button in vscode also

mystic marsh
#

yea its python <file dir>

robust fulcrum
#

press tab if you don't wana write full path 😂

mystic marsh
#

oh i wonder what u gotta do then

graceful haven
robust fulcrum
#

Its a path issue

graceful haven
#

and how do i fix that

graceful haven
robust fulcrum
#

Thats not issue

#

Bro pls revise , it's very hard to help in such way

civic reef
#

Any good resource to learn bot dev

#

?

graceful haven
#

i dont need anyway

robust fulcrum
civic reef
#

Okay

robust fulcrum
#

i recommend not to look into blogs on discord bots

mystic marsh
#

right click on config.json and click copy path

robust fulcrum
robust fulcrum
mystic marsh
#

well he should learn it

#

@graceful haven ^