#discord-bots

1 messages Β· Page 182 of 1

dusky ravine
#

the bot will join the discord server and channel etc, has all permissions

slate swan
#

I don't know why it doesn't work but I would advise you to change your on_message and instead do a @client.command

dusky ravine
#

ok lemme try that

slate swan
#

import commands form discord.ext

dusky ravine
#

how do i do that?

slate swan
#

and the third line to py client = commands.Bot(command_prefix"your_bot_prefix, intents=discord.Intents.all())

dusky ravine
#

and then i need to edit the rest?

slate swan
#

is the code from chatgpt?

dusky ravine
#

ofc

slate swan
#

ask him to change the code with a command instead of a on_message event

#

and try to understand btw

dusky ravine
#

k i got wait an hr

#

Too many requests in 1 hour. Try again later.

slate swan
#

lol

dusky ravine
#

ye

slate swan
#
import discord
from discord.ext import commands
import mysql.connector

client = commands.Bot(command_prefix=">",intents=discord.Intents.all())

TOKEN = 'your_bot_token'
CHANNEL_ID = 'your_channel_id'

cnx = mysql.connector.connect(
    host="your_host",
    user="your_user",
    password="your_password",
    database="your_database"
)

@client.command
async def register(ctx):
        accountname = message.content.split(" ")[1]
        discordid = message.author.id
        cursor = cnx.cursor()
        query = f"UPDATE account SET reg_mail = '{discordid}' WHERE username LIKE '%{accountname}%'"
        cursor.execute(query)
        cnx.commit()
        cursor.close()
        await message.channel.send(f"{accountname}'s account has been updated successfully!")

client.run(TOKEN)
#

indents are wrong bcz im on mobile

dusky ravine
#

what is the >

#

command_prefix=">"

slate swan
#

to invoke the command

#

it's a prefix

dusky ravine
#

so rename this? to !register?

slate swan
#

nah

#

ah yes u can !register instead of >register

#

just change the prefix in !

dusky ravine
#

kk

slate swan
#

i forgot () after client.command

dusky ravine
#

oho we got a step further

#

it's picking up the command

slate swan
#
@client.command()```
dusky ravine
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "register.py", line 21, in register
    accountname = message.content.split(" ")[1]
NameError: name 'message' is not defined

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
#

@client.command is definitely the way forward

#

@slate swan i fixed it with chatgpt

#

ty for your help

vocal viper
#

hi

#

help me

#

heyyyyy

tawny mantle
#
Traceback (most recent call last):
  File "C:\Users\hackt\Desktop\desktop\Exile\main.py", line 4, in <module>
    from views.contact import Confirm
ModuleNotFoundError: No module named 'views.contact'; 'views' is not a package```

**HELP**, GIVING NITRO IF FIX
jaunty hare
#

hey people, aiosqlite works with a database file right?

twilit coral
#

There is no package named "views" and hence no module named "contact"

#

Are you trying to import a library or are you trying to import a package from your pc? @tawny mantle

tawny mantle
#

dm @twilit coral

terse coyote
#

what?

terse coyote
vale wing
#

I mean is the cooldown individual for command or is it global

vale wing
#

!d discord.app_commands.checks.dynamic_cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

Both `key` and `factory` can optionally be coroutines.
tawny mantle
#

@terse coyote dm me

pastel basin
#

If...

#

My local machine time is 31st Jan (today), and I import datetime, what time will be for datetime?

white citrus
#

Is it possible to send a welcome picture made by the bot in a embed?

ebon island
#

Is there a way to permission gate on a cog by cog basis in slash commands? It was possible with regular commands but isn't working with the same code/implementation with slash commands

slate swan
#

yeah

scarlet aurora
#
            channel = self.bot.get_guild(payload.guild_id).get_channel(payload.channel_id)
            message = channel.fetch_message(payload.message_id)
            if str(payload.emoji) == "\U00002705":
                for user in message.mentions:```Can someone help?
#
                ^^^^^^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'mentions'
C:\Users\llVll\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py:348: RuntimeWarning: coroutine 'Messageable.fetch_message' was never awaited
  await self.on_error(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
vocal snow
white citrus
vocal snow
#

and he told you how, implying that it is possible

hollow gazelle
#

bot = commands.Bot(intents=discord.Intents.all(), command_prefix=f"{prefix}") Using pycord

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.

slate swan
#

.topic

lament depotBOT
#
**What feature would you like to see added to the library? What feature in the library do you think is redundant?**

Suggest more topics here!

slate swan
slate swan
#

ok so im trying to make a command where it would match up all nfl teams like the image below, heres the code i have so far ```@bot.slash_command(description="Generate a Schedule")
@application_checks.has_permissions(administrator=True)
async def schedule(interaction):
teams = ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants", "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Commanders"]
import random

teams = ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants", "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Commanders"]
home, away, test, three, = random.sample(teams, k=2) 
await interaction.response.send_message(f'{home} vs {away}\n{test} vs {three}')

I want it so it matches them up and doesnt re use a team twice. Any help?
slate swan
#

Check if the team is in list if not add it to message then send message

#

what do i append exactly

slate swan
slate swan
#
choice = teamz.append(random.choice)
teamz.pop(choice)
#

ok ill try it

#

don't append to new list

#

no reason u already have 2 list

#

pop will remove them from list

slate swan
#

this is the error

#

u already have the var for the choices

#

home away

#

so pop those two

slate swan
#

A man of taste

#

ok so just add home.pop

#
teams = []
home, away = random.sample(teams, k=2
teams.remove(home)
teams.remove(away)
slate swan
#

want me to keep the choice thing?

#

wait

#

its remove

#

not pop

#

ok

#

do i keep the choice =?

#

u dont need that

#

k

#

unless ur using for something else

#

u have a blank list

#

ik

#

i realized

#

u override teams

#

so this good

#

yes

#

ok how i can i get to to say all of the teams

#

and not just 2

#

for loop and sample 2 until list is empty

#

ok

#

i suggest using embed and adding fields

elder venture
#

I dont get whats wrong... am i blind?
Its raising this: 'discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction'

async def checkportscommand(interaction: discord.Interaction):
    await interaction.response.send_message(f'checking all Ports...')```
slate swan
#

its just

#

its just like repeating the same thing over

slate swan
#

yeah

#

thats why i suggesting using embed

#

its not changing it bruh

#

and adding fields

#

its the same team 2 teams every single time thats not the issue

#

cause ur not doing it right lol i suggest you learn python basics i gave u how to you just don't know how to properly

#

i legit know python basics

#

you don't or else you would know how to iterate properly lol

#

i do

#

..

#

not working

#

thats what its doing

#

i got it for like this but how can i print like the other

glad cradle
slate swan
#

no

#

slash command

#

what should i do

#

help

#

no offense but people aren't going to feed you code

#

im not trying to get fed code kid im legit asking for help

#

what am i doing wrong in the code

vocal snow
slate swan
#
teams = ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants", "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Commanders"]```
vocal snow
#

So why are you unpacking into home, away in the for loop

#

Do you want to split the string and get the first word into home and second word into away

slate swan
#

sure if thats a way

vocal snow
#

!d str.split

unkempt canyonBOT
#

str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).

If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.

For example:
slate swan
#

is there any other ways

vocal snow
#

That's picking two elements from the list

#

Which returns a list which can be unpacked

#

You're unpacking strings in the for loop

deep mirage
slate swan
#

yall read up

#

i told him how to do it he just wants the code fed

#

i dont want the code fed

#

im clearly asking for help

#

and i told you you should learn python basics

#

just leave tbh your no help ur just gonna say harmfull things

deep mirage
#

what do you expect/want it to send?

slate swan
#

not saying harmful things?

#

saying false things*

slate swan
# slate swan

you said you know how to iterate properly then proceeded to send this

#

does that mean i want the code fed?

#

i told you exactly how you can achieve what you want. you just don't know how to do it because you don't understand python basics

#

I do

deep mirage
vocal snow
slate swan
#

read up

slate swan
deep mirage
#

in a random order?

slate swan
#

yes

deep mirage
#

then dont use .sample, I recommend .shuffle and then iterating through two of them at the same time

slate swan
#

ok

#

what no

#

he is using 2 different list lol

deep mirage
#

he shouldnt be using home and away

slate swan
#

yes he should lmao

#

he has it working fine he just doesnt know how to iterate the list and match all teams

#

i do im clearly dopig it but just not like 2 time

#

like its printing the same team

#

because ur not iterating properly

#

this is error

#

there are multiple ways to do this

#

what are the ways

deep mirage
#

@slate swan I recommend just using .shuffle with list.join

slate swan
#

why would he shuffle lmao

deep mirage
#

because he wants them in a random order

slate swan
#

no he doesn't

#

read previous messages

deep mirage
slate swan
#

yes random order

#

do not use shuffle it is of no use to you as you are PICKING items at random out of the list and putting them against each other. all shuffle does is randomize the order of the list

#

stop misinforming

deep mirage
#

tahts what hes tryna do

slate swan
#

no it is not

vocal snow
#

Shuffle and use a range to iterate in groups of two

#

Makes sense to me

deep mirage
#
random.shuffle(teams)
await interaction.response.send_message('\n'.join(f'{teams[i]} vs {teams[i+1]}' for i in ...```
#

@slate swan you finish it

slate swan
#

ok

deep mirage
#

or interaction.send

#

idk what library that is

#

and you might wanna assert the length of teams is even

#

thats against tos my guy

slate swan
#

no one here is going to help with self botting

#

am i going in the right direction

deep mirage
slate swan
#

i really suggest you learning basics man. you're just going to keep hitting walls

deep mirage
slate swan
#

^

slate swan
#

stop saying that its so annoying

deep mirage
#

youre getting the item of teams at index i and index i+1, so that means you need to get an index at 0, 2, 4, 6 until the length of teams

slate swan
#

ur trying to iterate 2 variables

deep mirage
#

and I should indeed consider learning a bit more about iteration before trying a discord bot

slate swan
#

can i just do this length = len(list)

vocal snow
#

Have you used range() before

slate swan
#

no none my commands have required it

deep mirage
#

now thats obviously not correct

slate swan
#

o

vocal snow
slate swan
#
    for i in range(0, len(roles)):
        if roles[i].name in teams:
            team = roles[i]``` like this
#

ur literally just copying stuff at this point lol

#

what

#

i give up

slate swan
#

jaymart leave your not help at all no one cares πŸ˜‚

#

you just searched range in this discord and copied their code dude

#

nope thats in my code πŸ˜‚

#

your copying code bro

#

stop lying man

#

no im not LOOL

#

thats been in my code for so long

#

πŸ‘

#

πŸ˜‚

#

nice try though πŸ‘

steep wedge
slate swan
#

idc what you think if ur not boutta help dont talk

#

didnt even know that was there

scarlet aurora
#

can someone tell me how I can make the bot ignore it's own reaction

#

on a cog.listener payload

silent ermine
vale wing
#

What the hell

vale wing
#

And uses ineffective searching for named roles

#

Anyway shouldn't be searching roles by name in most of cases

#

This isn't as useless as "{}".format(string_instance) but still why do list comp here when you can just use utils.find() (and yeah doesn't have break when team is assigned which is weird)

team = nextcord.utils.find(lambda r: r.name in teams, interaction.user.roles)```
#

Actually even without using this function you don't need list comp there

team: str | None = None
for role in interaction.user.roles:
    if role.name in teams:
        team = role.name
        break
assert team is not None```
ebon island
slate swan
#

oh perfect

#

i have an easy solution for you

naive briar
#

Imagine

slate swan
#
class AdminCommands(Cog, slash_command_attrs={"default_member_permissions": disnake.Permissions(administrator=True)}):

@ebon island

#

so now all commands within that cog require the administrator permission by default

ebon island
#

ooh, interesting, so I'm a little confused about how to wrap that around the cog class though, can you should a little more detail in the snippet for context?

#

Thank you btw!

naive briar
#

You set the meta class option in the class definition

ebon island
#

ohhhh I think I understand, let me try

slate swan
#

yea it's fairly simple and not much to it

ebon island
slate swan
#

no problem!

neat pagoda
#

I just thought I’d put this out here for anyone struggling

#
import discord
from discord.ext import commands

# Initialize bot
bot = commands.Bot(command_prefix="!")

# Assign a channel for mod mail
mod_mail_channel_id = 123456789 # Replace with an actual channel ID

# Command for users to send to mod mail
@bot.command()
async def modmail(ctx, *, message: str):
    # Sends the message to the designated mod mail channel
    channel = bot.get_channel(mod_mail_channel_id)
    embed = discord.Embed(title="New Mod Mail Received", description=message, color=0x00ff00)
    embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
    embed.set_footer(text=f"Sent by {ctx.author} from {ctx.guild}")
    await channel.send(embed=embed)
    await ctx.send("Your message has been sent to the moderation team.")

bot.run("YOUR_BOT_TOKEN")

It’s a fairly simple mod mail bot code that I created a little while back

slate swan
#

sure but how is anyone supposed to respond?

ebon island
#

Haha so I might be asking for Christmas gifts twice in one day but is there a cogwide cooldown handler?

fading marlin
#

inb4

TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
slate swan
#

u can then use this

#

inside of that

class Vanity(AutoShardedInteractionBot):
    def __init__(self):
        self.pCooldown = commands.CooldownMapping.from_cooldown(
            1, 120, commands.BucketType.user)
bucket = self.bot.pCooldown.get_bucket(inter.author)
if retry_after := bucket.update_rate_limit():
    return
fading marlin
#

disnake is cursed

slate swan
#
async def cog_slash_command_check(self, inter: AppCmdInter):

this is all you need btw for the cog slash check

slate swan
fading marlin
#

Naming stuff really. What's AutoShardedInteractionBot and why have the "Interaction" in there pithink

slate swan
#

and because you have interaction bot and normal bot.

fading marlin
#

Yikes

slate swan
#

?

terse coyote
#

how to do global cooldown for all app_commands but for one user?

slate swan
#

custom cooldown

fading marlin
# slate swan ?

Just seems weird to have 2 classes for bot. The way most forks rework the implementation of dpy always surprises me

terse coyote
slate swan
fading marlin
#

Β―_(ツ)_/Β―

slate swan
#

how can i see the user who invited the bots guilds the user is with

#

oauth

#

how

#

u get the data when they authorize when oauth

#

where can i see the data]

#

where data go

golden portal
#

!d discord.AuditLogAction.bot_add

unkempt canyonBOT
golden portal
#

only through guild.audit_logs

slate swan
austere vale
#
  #purge command
  @nextcord.slash_command(description="Purges a number of messages from a channel. Max messages 100.")
  @application_checks.has_permissions(manage_channels=True)
  async def purge(self,ctx,*,number:int):
    deleted=await ctx.message.channel.purge(limit=number)
    await ctx.send(f'Messages purged by {ctx.message.author.mention}: `{len(deleted)}` (max is 100)')

can someone help me with this error please? i am trying to make a slash purge command. My intents are intents=nextcord.Intents.all())

0|bot  | Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7f9853f90ac0>:
0|bot  | Traceback (most recent call last):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 906, in invoke_callback_with_hooks
0|bot  |     await self(interaction, *args, **kwargs)
0|bot  |   File "/home/Runa/bot/cogs/moderation.py", line 20, in purge
0|bot  |     deleted=await ctx.message.channel.purge(limit=number)
0|bot  | AttributeError: 'NoneType' object has no attribute 'channel'
0|bot  | The above exception was the direct cause of the following exception:
0|bot  | nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
slate swan
#

it would be ctx.channel.purge

#

i also advise using interaction rather than ctx

austere vale
slate swan
#
self, interaction

also u typehinting will help alot

austere vale
#

what difference does it make by using interaction instead of ctx?

#

is it faster?

slate swan
#

no its just a naming. its better to keep interactions and ctx seperated

#

it always uses interaction, you're just naming it wrong

slate swan
#

make sure you don't have multiple environments

austere vale
#

ahh i see. do you know what i should use instead of {ctx.author.mention}? it says AttributeError: 'Interaction' object has no attribute 'author'

slate swan
#

.user

austere vale
#

got it! thank you both so much

ebon island
#

What is the best library currently available/supported for use with Disnake for playing mp3s? Really want one that on demand returns the track position and has seek functionality. I don't want or need anything like YT etc, all of the mp3s will be sourced from a local library. Quite curious what my options are in that regard πŸ™‚

slate swan
#

i used wavelink when i did a music bot

ebon island
#

I'll look into it! Thanks, I also saw discord-ext-music but last commit was Oc 19 22 and only 5 stars so not sure if it's at all a viable option

vale wing
ebon island
#

That works?

vale wing
#

No need for wavelink at all

vale wing
ebon island
#

Oh wow, where can I read docs about doing that?

vale wing
#

That's the neat thing, there are no docs

#

However there's me

ebon island
#

hahaha relatable πŸ˜„

#

okay, so if I have imported/installed disnake base package, do I need to specify [voice] as you indicated or will it already be contained therein?

slate swan
#

you need to specify.

vale wing
#

You need to specify it explicitly

#

It will install PyNaCl for voice support

#

Just additional dependencies

ebon island
#

could you show me a short code snippet including imports and loading an mp3 from a filepath, then calling the track position method and calling seek?

#

I'll give it a try ASAP, really appreciate the info btw!

#

atm I've got people testing a feature in my dev build of the bot so I can't immediately test

vale wing
#

I need to recall how to do that give me a minute

slate swan
#

ffmpeg is very basic and not as flexible as wavelink which is why I suggested it.

ebon island
#

haha sure, thank you!

vale wing
#

!d discord.VoiceClient.play

unkempt canyonBOT
#

play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").

The finalizer, `after` is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.

Changed in version 2.0: Instead of writing to `sys.stderr`, the library’s logger is used.
slate swan
#

with wavelink you already have built in tracks, queues and some other stuff.

sick birch
#

like 80% of the github issues currently are about the voice protocol

#

not sure if there's a strong correlation there but it's something

vale wing
#

That's disnake tho

ebon island
#

so I am already using VoiceClient.play() in my existing code - how do I seek or get the current track position?

slate swan
#

you have to code that yourself

vale wing
#

I am currently searching docs wait

ebon island
#

how would I go about that?

#

I didn't see an obvious hook into doing so

slate swan
#

there is no built in track position or seek method

#

that's why i suggested wavelink.

ebon island
#

I thought wavelink was primarily aimed at YT and similar?

slate swan
#

no

ebon island
#

am I mistaken?

slate swan
#

also those voice bugs are in disnake too. it has to do with voiceclient.is_playing() returning True even if audio has stopped.

#

some weird stuff

ebon island
#

yeah

#

I have experienced that

slate swan
#

docs are pretty nice tho

ebon island
#

I'm going to look into it tomorrow for sure, appreciate the suggestion πŸ™‚

vale wing
#

Pretty sure I've seen wavelink/lavalink as ToS breaking services

ebon island
#

I think because of the YT usage

#

I know Groovy got shut down cease and desist style for that

#

hence why my bot is using only community sourced instrumentals

slate swan
#

nah it's not against tos

ebon island
#

I want no part in that riff raff with Alphabet suing us into oblivion

slate swan
#

what's against tos is playing YT music

#

yall know whats funny. mee6 still has those capabilities lmao

ebon island
#

haha yeah

#

I don't know how some of them, and relatively large bots are still doing that

#

the vast majority have removed YT functionality

#

I know this very well as my niche community music centric

slate swan
#

mee6 runs discord lol

fickle hamlet
#

TFW when mee6 breaks discord TOS

vale wing
#

Anyways if you want to do that with bare ffmpeg

  1. Install ffmpeg executable (on linux that's just sudo apt install ffmpeg on windows download it from https://ffmpeg.org/ and add to path)
  2. In code just do this
voice.play(disnake.FFmpegPCMAudio("path/to/music")```
@ebon island
ebon island
#

yep I have that in my code already actually exen πŸ˜„

#

the issue is I don't see any way I can natively seek/get position atm

#

that'd be a great feature to see for sure

vale wing
slate swan
#

longevity

vale wing
#

Can't even detect amogus if you say amoguss

#

Probably have if any(word in content.split() for word in blacklist) πŸ’€

fickle hamlet
fickle hamlet
#

Maybe they could actually tokenize but if their lazy difflib would be good enough tbh

ebon island
#

I have my own means of creating a queue

vale wing
#

Issue with difflib is it would probably detect all words that end with *uck like duck as blacklisted

fickle hamlet
#

You can use context parsing with difflib

#

Not built in but custom

ebon island
#

it's a 24/7 instrumental music bot for hip hop/rap cyphers

vale wing
#

I have words filter that is nicer than mee6's and most of bots' but due to wildcard checking it sometimes detects blacklisted words in not blacklisted ones which is an issue

#

I haven't actually thought of using difflib

fickle hamlet
#

I forgot the time complexity but it should be higher than O(n)

#

But I’m sure if you can do something like an LALR parser then difflib it would be powerful

ebon island
#

was that difflib intended to be a response to my message? lol

vale wing
#

Why would it be higher than O(n) tho

#

Def not

ebon island
#

I am quite certain it wasn't haha

#

but I just saw you replied to me with it so I was confused πŸ˜›

fickle hamlet
#

Because you compare for each string inside of a sentence, then you compare each position of the tokens

slate swan
#

just use openai moderation endpoint

slate swan
vale wing
#

Aren't openai's APIs paid

slate swan
#

nah openai endpoint way better than discord auto mod

vale wing
slate swan
#

they have paid version yeah

vale wing
#

Open one probably has ratelimits

slate swan
#

but there is free usage as well

fickle hamlet
slate swan
#

they all have ratelimits

vale wing
#

So if the bot reaches limit it breaks, who needs that

fickle hamlet
#

Yea time complexity of the algorithm is O(n^3) or O(n^2)

vale wing
#

Real bad

slate swan
fickle hamlet
#

I would hope moderation bots could be used in large guilds otherwise that would kinda break the point

vale wing
#

There's no that issue as I am not gonna use it

slate swan
vale wing
#

It breaks not because of bot but because of limit

fickle hamlet
#

???

vale wing
#

Developers can use whatever solution

fickle hamlet
#

Yea ^^^

slate swan
fickle hamlet
#

Not sure how’d you’d scale a third party API

slate swan
#

.....

#

nobody said anything about scaling a third party API lol

fickle hamlet
#

But your idea relies on OpenAI which as a limit

vale wing
#

We are talking that using third party API that has limits is unsuitable for bot that does not put any limits on users

fickle hamlet
#

The β€œscalability” you are talking about would require to upgrade your API key

slate swan
slate swan
fickle hamlet
#

Lmao, your logic doesn’t follow

ebon island
#

headed to bed, appreciate the tips, I'm going to dig into wavelink tomorrow to give it a try and see how it serves my purpose πŸ™‚

slate swan
#

my logic is scaling your bot has nothing to do with limits on a API

vale wing
slate swan
vale wing
#

If 100 users send the message at the same time discord will process that (unless it lags)

fickle hamlet
#

I’m not sure how scaling your bot that relies on an outside API to be optimal

slate swan
fickle hamlet
#

Mmmm, yes let’s just pay to get a premium API

slate swan
#

so you don't pay to host ur bot?

fickle hamlet
slate swan
#

or pay to upgrade the host

#

for scaling?

fickle hamlet
#

I’m not sure whyd I need more memory, CPU etc for a bot that just posts to an API then decides whether or not to delete the message

slate swan
vale wing
#

Buy a host with GPU and get your own local model (that's gonna be 1k$+ per month probably but who cares)

fickle hamlet
#

The only thing hardware wise you would need more of is bandwidth

vale wing
#

How do you even promote the bots

slate swan
slate swan
vale wing
#

Ok ig ima just embed vote webhook into bot

slate swan
#

it's really just passive promotion

vale wing
#

And add a tip

fickle hamlet
#

Sure upgrading memory would help with cache as well

slate swan
vale wing
vale wing
#

πŸ€“

fickle hamlet
#

This man is speaking in Minecraft enchanting table

vale wing
#

I once set my font in code editor to minecraft enchantment

slate swan
fickle hamlet
vale wing
#

That was uh magic

fickle hamlet
slate swan
#

just curious, and how did you handle it?

fickle hamlet
#

You cluster and add a caching system

#

But also load balancers too

slate swan
#

sure how u gonna add a cache system on a 2gb ram host tho?

#

that's right you need to UPGRADE

slate swan
#

which is the point i was making the entire time

fickle hamlet
#

Again, if you really want to nitpick you can invalidate that point by restricting discord.py’s automatic message caching

#

Since you don’t need data to persist long enough, just enough for the API to determine whether or not to moderate

vale wing
#

Do you think this activity is alright

slate swan
#

wtf

#

the miniscule server increase makes the graph look dumb. but its not bad most ppl can't even do that in a month

fickle hamlet
#

Since your bot solely relies on a third party API

slate swan
#

nobody said it solely relies on a tpAPI tho lol it was a suggestion that turned into " why use this if im going to get limited"

#

and i said thats a you issue as scaling your bot is your problem. if your bot doesn't scale ur fine otherwise you need to adapt

fickle hamlet
#

πŸ˜‚

sick birch
torn sail
#

Are there any popular cogs like jishaku that I can download and add to my bot easily?

shut elk
#

What can be a potential cause to unknown interaction happening to await defer, despite it being in the first line

#

Is the only reason that the server is slow?

slate swan
shut elk
shut elk
slate swan
#

your internet might be slow

#

or some part of your code is blocking, causing the request to be sent late

vale wing
unkempt canyonBOT
shut elk
vale wing
#

It makes code readable

shut elk
#

mk

unkempt canyonBOT
#

Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

shut elk
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

upbeat gust
#

The error says what's wrong

slate swan
loud junco
#

i still have no idea on how to import variables like area and highestArea from another file

#

if i use class init: it cant be async but define bot
if i use function: can be async but cant define bot

vocal snow
#

and there's also ctx.bot or something iirc

loud junco
vocal snow
loud junco
#

or just ctx.bot.database_handler

loud junco
loud junco
slate swan
#

you didn't await the function

loud junco
#

wait πŸ’€

shut axle
#

Pls help me

#

How can i solve it?

#

I have a problem with the cogs

naive briar
#

Read the error

#

The load_extension method is now a coroutine

shut axle
#

Like that ?

slate swan
#

the code:

import discord
import random
import string
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)

@bot.command()
async def check(ctx):
    await ctx.send("Checking...")
    available_usernames = []
    for i in range(15):
        username = ''.join(random.choices(string.ascii_letters, k=10)) + "#0001"
        print(f"Checking {username}")
        try:
            user = await bot.fetch_user(username)
            if user is None:
                available_usernames.append(username)
                print(f"{username} is available!")
            await asyncio.sleep(1)
        except:
            pass
    if available_usernames:
        embed = discord.Embed(title="Available Usernames", description="\n".join(available_usernames), color=0x00ff00)
        await ctx.send(embed=embed)
    else:
        await ctx.send("No available usernames were found.")

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    print(f'With the ID : {bot.user.id}')

what im trying to achieve: a successful discord username checker bot, however it just doesn't seem to work. @hollow quarry

frosty umbra
#

what do you mean by a username checker bot

slate swan
#

it checks the random strings as you can see it randomly generates a length of 10

#

#0001 discriminator

frosty umbra
#

so you want it to check if a username and tag is available ?

slate swan
#

correct

frosty umbra
#

I think the main issue would be trying to fetch users that aren't in your discord server

slate swan
#

oof

frosty umbra
#

I don't believe you can fetch every single user on discord

#

And it would take a while

slate swan
#

hhhhhhhh

#

idk anymore

#

@frosty umbra look at this

#

thats exactly what im tryna do. 😦

frosty umbra
#

Those are users in the server

#

or in a server with the bot

#

I assume

slate swan
#

so you're telling me i need to either:

  1. make a community with a lot of users
  2. convince people to add my bot to their server
frosty umbra
#

I'm sort of confused for the usage of this

#

What use does looking up all users with a certain tag have

slate swan
#

to get an og user

#

like covid#0001

#

og.

frosty umbra
#

u can get that?

#

just have nitro no?

slate swan
#

there is a way to get 0001 discriminator's but i am not allowed to discuss that here.

#

however nitro, yes.

frosty umbra
#

i already know how

#

I still wouldn't see a need for og usernames on discord

#

considering you can just have the username with a different tag

slate swan
#

na na na

frosty umbra
#

wha

#

how

slate swan
#

lets say you want Fiery#0001, but i have it.

#

????????????

frosty umbra
#

that means i cant have it

slate swan
#

exactlyyokwekgegkowgs

frosty umbra
#

I think even with nitro

#

it might change your discriminator

slate swan
#

it doesnt

#

if you have nitro you can do that yourself, why bother using these tricks lol

#

it says the username aint available

frosty umbra
slate swan
#

my god can i please speak to someone with an iq higher than 50 😭

frosty umbra
#

bro

#

your trying to fetch every single user on discord...

#

it just doesnt work

slate swan
#

i wouldn't be the one judging other's IQs if i was in a help channel asking for something that isnt possible

#

im leaving

frosty umbra
#

me after telling someone its not possible and they get angry

slate swan
#

bots like dyno and whatever bot's ss you sent above use their internal cache to provide that list

#

i.e. they have tons of users with that discriminator with them already, they're not fetching it

frosty umbra
#

ye

#

They probably take it from a list of users that the bot shares a guild with?

slate swan
#

right

frosty umbra
#

which i said earlier btw

slate swan
#

atleast that's what dyno does

frosty umbra
#

its not possible to fetch from all users on discord so probaby most other bots do the same

loud junco
slate swan
#

it does

young dagger
#

Which database software should I use for hosting my own database on my VPS, currently using MongoDB Atlas?

wanton spoke
loud junco
loud junco
loud junco
wanton spoke
slate swan
#

vsc supports py 3.11

#

so all versions below that should also be supported

#

are you sure you have 3.10+ installed? @loud junco

loud junco
slate swan
#

no.. your python version

slate swan
#

yes you can, but we can't help you with that here if you're planning to use youtube for that

#

or any other application that doesnt allow bots

#

!ytdl

unkempt canyonBOT
#

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)
slate swan
#

do you have a proper knowledge of asyncio and OOP?

#

even spotify doesnt allow bots streaming

#

soundcloud does, as long as you're not downloading the songs

#

this is a basic example

#

yeah

#

but you can use the same format for most applications

upbeat otter
#

what's the point of making a music bot pepe_exit

potent spear
upbeat otter
#

most of them use ytdl

#

nvm that's not a valid reason

potent spear
#

mhm

cloud dawn
upbeat otter
#

yes

cloud dawn
#

Like if don't use youtube what's the point

potent spear
#

isn't lavalink a ||better?|| alternative?

cloud dawn
#

ewwie java

upbeat otter
#

and uses youtube again to get music

slate swan
#

😎

slate swan
upbeat otter
#

that may still break the host's TOS

slate swan
#

lavalink servers can be hosted anywhere, doesnt really have to be the same host as ur bot

#
  • soundcloud allows streaming, so y not
cloud dawn
#

Soundcloud does?

pastel nimbus
cloud dawn
unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
β€’ Decorators (see !tags decorators)
β€’ Inheritance (overriding methods)
β€’ Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
β€’ Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

#

Positional vs. Keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Somtimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
β€’ Keyword only arguments
β€’ Positional only arguments
β€’ !tags param-arg (Parameters vs. Arguments)

slate swan
pastel nimbus
#

TypeError: init() missing 1 required keyword-only argument: 'intents'

maiden fable
#

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

slate swan
#
  File "/home/asterv2/site.py", line 1, in <module>
    import discord
  File "/home/asterv2/.local/lib/python3.9/site-packages/discord/__init__.py", line 20, in <module>
    import logging
  File "/usr/lib/python3.9/logging/__init__.py", line 26, in <module>
    import sys, os, time, io, re, traceback, warnings, weakref, collections.abc
  File "/usr/lib/python3.9/traceback.py", line 5, in <module>
    import linecache
  File "/usr/lib/python3.9/linecache.py", line 11, in <module>
    import tokenize
  File "/usr/lib/python3.9/tokenize.py", line 34, in <module>
    from token import *
  File "/home/asterv2/token.py", line 8, in <module>
    from ctypes import windll, wintypes, byref, cdll, Structure, POINTER, c_char, c_buffer
ImportError: cannot import name 'windll' from 'ctypes' (/usr/lib/python3.9/ctypes/__init__.py)```
#

guys can u help me with this error?

#

everytime i run a code from terminal this will pop up

#

ctypes.windll doesn't exist

#

yes i also tried to install windll

#

but that still pops up

#

!d ctypes.WinDLL

unkempt canyonBOT
#

class ctypes.WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)```
Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the `stdcall` calling convention, and are assumed to return int by default.
slate swan
#

python is case sensitive

#

ohh

#

thanks thanks

pastel basin
#

Hello, I am hosting my bot GMT timezone but I want it to be Pacific timezone. How can I change it?

#

@slate swan

slate swan
unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
slate swan
#

takes tzinfo in argument

pastel basin
#

!tzinfo

#

!tz

forest oyster
#

I have a problem with my discord bot, everything is ok, but it doesnt show the button, heres the code:
@bot.command()
@commands.has_permissions(administrator=True)
async def ticket(ctx):
await ctx.message.delete()

embed = discord.Embed(title ='Tickets', description ='Bienvenido al sistema de tickets.', color=discord.Color.green()) 
embed.set_image(url='https://cdn.discordapp.com/attachments/1065041520572514304/1065341200950894783/Banner_tickets.png%27)

await ctx.send(
    embed = embed,
    content = [
        discord.ui.button(
            label="Crear un ticket",
            custom_id="Ticket", 
            style=discord.ButtonStyle.success, 
            emoji='πŸ”§')
    ]
)
#

it responds this:
[<function button.<locals>.decorator at 0x00000239091BDA20>]

#

can someone help me?

loud junco
forest oyster
#

the problem must be here:

forest oyster
#

because theres the buttom

#

but idk where

#

and why

slate swan
#

im pretty sure its .Button

loud junco
slate swan
#

lowercase is for the decorator

#

upper case is the class

forest oyster
# slate swan im pretty sure its `.Button`

by the way if i put Button, the bot responds this: [<Button style=<ButtonStyle.success: 3> url=None disabled=False label='Crear un ticket' emoji=<PartialEmoji animated=False name='πŸ”§' id=None> row=None>]

slate swan
#

wait what lib are u using?

forest oyster
slate swan
#

is this a slash command?

#

no

#

so ctx doesn't have low level components

#

you can't do that in dpy

#

@forest oyster you need to send as a view

forest oyster
slate swan
#

view=view

#

also use the docs

forest oyster
#

ooooo ok

slate swan
#

how can i see the user who invited the bots guilds the user is with

forest oyster
#

thanks, im going top try it

ebon island
#

@slate swan Trying out Wavelink - how do I install base Lavalink atm? I tried downloading the .jar but was unable to find it, has that method changed?

#

Also, experiencing an issue where codeblocks in embedded messages are not displaying correctly on iphone, is this a known issue?

slate swan
#

you just pypi it

slate swan
#

how can i make a command so that when someone authorizes with my bot and They allow the bot to join servers for them, and if they leave the server i can run a command that will pull them back in

#

also that gh link has the lavalink.jar at the bottom

slate swan
#

what should i look up

#

restore bot

#

ok

slate swan
sick birch
slate swan
#

lmfao

ebon island
#

@slate swan So then how do I configure the lavalink server? Getting the following:

Connection Failure: Cannot connect to host 0.0.0.0:2333 ssl:default [The format of the specified network name is invalid]
#

seems like the format of the network is fine

#

and should do localhost

slate swan
#

did you change the app.yml?

slate swan
#

you have any traceback at all?

#

in my code When I type A number of 0 - 10 my code is starting to send me messages for when gonna 10 messages
but if != 10 and anyone come's after me and typed number it's not sending messages to him and the client doesn't work != 10.

#

at discord bot how can I do this

slate swan
#

like think a message sender bot

#

.message <how much>

#

I am gonna type .message 5

#

and it's starting to typing messages

#

but slowly don't think like (". . . . .") it s like (".") (".") ... if the messages not equal to 5 it's sending when it's equal it's stopping.

#

but think like that when My message count is 2

#

the anyone come and type .message blabla

sick birch
#

Ah, like a loading dot thing?

slate swan
#

the client just sending to me

slate swan
#

and the client can't see his messages

#

I need help at this

#

here is my code wait

#
@client.event
async def on_message(message):
        
        if len(message.content.split(" ")) == 2 and message.content.split(" ")[0] == ".message":
            await message.delete() #delete user messages
            channel = client.get_channel(1061705379064582204)
            await channel.send("**{} in {}: {}**".format(str(message.author), message.guild.name, message.content))
            print('gânderim başarılı.') #send log
            if len(message.content.split(" ")[1]) == 10:
                telno = message.content.split(" ")[1] #telling number
                embed=discord.Embed(title="**MesajcΔ± [8138] ** ", description=(f"**{adet} adet mesaj GΓΆnderiliyor  -->  #sending message**\n{message.author.mention}"), color=0x001eff) #sending messages
                message = Sendmessage(id, "")
                await message.channel.send(embed=embed)
                while mesagge.adet < adet: # adet = 55
                    for attribute in dir(Sendmessage):
                        attribute_value = getattr(Sendmessage, attribute)
                        if callable(attribute_value):
                            if attribute.startswith('__') == False:
                                if message.adet == adet:
                                    break
                            exec("message."+attribute+"()")
                            sleep(saniye)
#

it's not all

#

but some part of it

#

@sick birch :(

sick birch
#

You can only edit a message a few times in 5 seconds

slate swan
#

oh

#

sorry

#
@client.event
async def on_message(message):
        
        if len(message.content.split(" ")) == 2 and message.content.split(" ")[0] == ".message":
            await message.delete() #delete user messages
            channel = client.get_channel(1061705379064582204)
            await channel.send("**{} in {}: {}**".format(str(message.author), message.guild.name, message.content))
            print('gânderim başarılı.') #send log
            if len(message.content.split(" ")[1]) == 10:
                telno = message.content.split(" ")[1] #telling number
                embed=discord.Embed(title="**MesajcΔ± [8138] ** ", description=(f"**{adet} adet mesaj GΓΆnderiliyor  -->  #sending message**\n{message.author.mention}"), color=0x001eff) #sending messages
                message = Sendmessage(id, "")
                await message.channel.send(embed=embed)
                while mesagge.adet < adet: # adet = 55
                    for attribute in dir(Sendmessage):
                        attribute_value = getattr(Sendmessage, attribute)
                        if callable(attribute_value):
                            if attribute.startswith('__') == False:
                                if message.adet == adet:
                                    break
                            exec("message."+attribute+"()")
                            sleep(saniye)
#

it's my code @sick birch

sick birch
#

There isn't much you can do

slate swan
#

can you edit my code

#

for me pleasee

#

or give me a sample

sick birch
slate swan
#

oh

vale wing
#
if a == 1:
    if b == 2:
        if c == 3:
            if d == 4:
                print("ohh I love this stuff")
upbeat otter
vale wing
#

That's sarcasm

slate swan
vale wing
#

πŸ€“

#

How long you typed it for

slate swan
#

14 secs

primal token
#

match case scopes😈

primal token
slate swan
#

ik how to copy paste and use tabs

vale wing
#

First edition sounded funnier

primal token
#

sussy

upbeat otter
vale wing
#

!e

print("\n".join("    " * i + f"match {l}:\n{'    ' * (i + 1)}case {i // 2 + 1}:" for i, l in zip(range(1, 20, 2), __import__("string").ascii_lowercase)))```
#

That actually worked

unkempt canyonBOT
#

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

001 |     match a:
002 |         case 1:
003 |             match b:
004 |                 case 2:
005 |                     match c:
006 |                         case 3:
007 |                             match d:
008 |                                 case 4:
009 |                                     match e:
010 |                                         case 5:
011 |                                             match f:
... (truncated - too many lines)

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

vale wing
lament depotBOT
slate swan
#

lmao

primal token
vale wing
#

No tabs in python!

slate swan
lament depotBOT
vale wing
#

Generated code is PEP compliant

#

(no)

slate swan
#

print("\n".join(" " * i + f"match {l}:\n{' ' * (i + 1)}case {i // 2 + 1}:" for i, l in zip(range(1, 20, 2), import("string").ascii_lowercase)))

feral frost
#

Code

# <--------------Import-------------->
import asyncio
import contextlib
import io
import json
import os
import random
import sqlite3
import string
import sys
import textwrap
from code import interact
from cProfile import label
from datetime import datetime, timedelta
from io import BytesIO
from operator import ne
from tkinter import Button
from traceback import format_exception
from unicodedata import category
from webbrowser import BackgroundBrowser

import numpy as np
import requests
from discord import Intents, ui
from discord.ext import commands
from discord.ui import Button, Select, View
from nturl2path import url2pathname
from PIL import Image, ImageDraw, ImageFont
``` just some imports 
and i get this error anyone knows what i did wrong ?
```line 24, in <module>
    from discord import Intents, ui``` because when i delete that line it keeps the error on line 24 so idk what there is wrong
slate swan
#
print("\n".join("    " * i + f"match {l}:\n{'    ' * (i + 1)}case {i // 2 + 1}:" for i, l in zip(range(1, 20, 2), __import__("string").ascii_lowercase)))```
vale wing
feral frost
#

always an error on line 24

vale wing
#

About error, is the venv configured properly

feral frost
#

idk where can i see that ?

vale wing
#

Bottom right corner

feral frost
#

is it the interpreter

#

like why on line 24

#

just came back after a while i didnt touch anything and i randomly get an error

#

tried resetting the token

feral frost
slate swan
#

One second.

#

Ill help you

feral frost
slate swan
#

Hold on

feral frost
#

oki

#

take your time

slate swan
#

There are a few issues with this code:

  1. There are multiple imports with the same name, such as from tkinter import Button and from discord.ui import Button. This can lead to confusion and errors when trying to use the imported module.

  2. Some of the imports are not used in the code and are unnecessary, such as from code import interact, from cProfile import label, from operator import ne, from traceback import format_exception, from unicodedata import category, from webbrowser import BackgroundBrowser, from nturl2path import url2pathname, from PIL import Image, ImageDraw, ImageFont.

  3. Some of the imports are not compatible with the discord library, such as import numpy as np, import requests, from PIL import Image, ImageDraw, ImageFont. These libraries are not designed to work with discord and will likely cause issues if used with discord.

4.There is no code that uses these imports, this imports are just taking space and are not doing anything.
I would recommend removing any unused imports, and double-checking that any imports that are used are compatible with the discord library.

Additionally, the imports should be grouped in a logical way, for example, all the discord imports should be together and all the standard library imports should be together.

feral frost
#

ok i removed all the unused imports, multi imports, etc but i still get the same error maybe something is wrong with that import but when i remove it it just goes to to the import under it

slate swan
#

Send the new code.

#

ok

feral frost
#

wait i fixed it huh

slate swan
#

Good job.

feral frost
#

wow well thanku for your help πŸ™‚

slate swan
#

No problem.

feral frost
#

just had to reinstall discord

slate swan
#

Is there a issue with that?

#

theres the answer

#

AttributeError: 'Bot' object has no attribute 'add_roles'

#

you can't add roles with a bot object it's not possible

#

are you trying to specify a specific bot to add the roles?

#

why not shard? or use clusters tho spawning multiple bot instances isn't going to help much

#

and i don't even know how you would specify which bot to perform a said action such as adding a role to a member

#

it doesn't work like that tho

#

you have ur event running through the main client

#

so that is what is specified to add roles

#

again i suggest you look into sharding/clustering

#

i believe what you are trying to do is cluster but the way you are doing it im not sure if that's the most plausible way

iron sorrel
#

guys how do i make a persistent button for reaction role verification?
so when i turn the bot off and on, the button callbacks are still valid

iron sorrel
slate swan
iron sorrel
#

dpy 2.0

slate swan
#

its not mis informing, thaats just one way

#

no it is not dude?

iron sorrel
#

there are better ways i bet

slate swan
#

One way to make a persistent button for reaction role verification is to store the callback data in a database that is not associated with the bot's runtime environment. This could include a remote database service like MongoDB or MySQL, or even a simple JSON file that is read and written to by the bot. Additionally, it would be important to implement some form of user identification, such as a unique user ID, to ensure that the callback data is only applied to the correct user. This way, when the bot is turned off and on, the callback data can be loaded from the database and reapplied to the correct user, allowing the button callbacks to remain valid.

#

using a database is not a way to make a button persistent lmao

#

Yes it is.

iron sorrel
slate swan
iron sorrel
slate swan
#

Its an answer no?

#

idc this kid been at it since yesterday man

iron sorrel
#

can we stop arguing, and talk about code

iron sorrel
slate swan
#

keeps misinforming ppl and copy pasting others code

iron sorrel
slate swan
#

then asking why the pasted code doesn't work

#

I named a way on how you can, and this kid is angry for no reason.

slate swan
#

that literally does not work lmao

#

Yes it does.

iron sorrel
slate swan
#

how does a database make a persistent button lmao

iron sorrel
#

jaymart, no point in that arguint, can you help me tho

slate swan
#

ANYWAYS set the timeout to none and assign a custom_id

#

and where will the custom id be stored

iron sorrel
slate swan
slate swan
#

holy shit

#

i cant can this kid be banned from this chat

iron sorrel
fading marlin
#

Calm down

slate swan
#

Jay can cry more im just giving an answer and hes crying over it.

iron sorrel
slate swan
#

and misinformed answer that does not work

slate swan
iron sorrel
#

but that is still not an answer i was looking for

slate swan
#

YOU DONT NEED A DB

#

I never said you need one, I suggested that as one way.

fading marlin
#

You do need a database if you want to make the persistent view work regardless of the guild. If you're just making it for a single server, you don't require one because you can just hardcode the custom ID

slate swan
slate swan
#

what the fuck

slate swan
#

you're welcome man

iron sorrel
#

for these kinda things

slate swan
#

I will be reporting jay with the modmail now.

#

no use. they wont remove them from chat from misinforming they would just tell them to stop lol

iron sorrel
#

jay was a lil not nice but, thats ok

slate swan
#

yesterday we was helping this kid and he kept asking and we told him and he was spamming chat waiting for someone to feed code. so someone gave him half of some fed code and he still couldnt get it to work. i suggested learning python basics he said he does but couldnt understand how to iterate. then he copied someones code pasted it and asked why it didn't work

#

now he is misinforming people

fading marlin
# slate swan what? no u dont lmao

If you have the same view across multiple guilds with the SAME custom ID, the view is gonna respond in a non-unique way. If you add a role from one guild, it will be accessible from any other and the verification thingy will become pretty pointless and useluess

slate swan
#

the custom_id only IDENTIFIES the button lmao

#

the interaction is a per guild basis

#

not a per bot basis wtf are u saying/

#

without custom_id the bot can not identify the button

iron sorrel
fading marlin
#

You still have a custom ID, it's just not hardcoded

slate swan
#

?

#

that is dynamic

fading marlin
#

Yup

slate swan
#

which is why setting a static one allows u to reuse the button even when restarting

fading marlin
#

Which is why you save the custom ID in a database... hence you need a database

slate swan
#

what the fuck are you talking about

#

all he wanted was to make the button persistent

slate swan
#

i even sent the EXAMPLE FROM DPY ITSELF

#

lmao where does it show or tell you to use a db?

#

There are multiple ways to doing this, we are simply suggesting one way. Who said that wasnt a way?

#

you didn't suggest shit. u asked chatgpt which again is banned from here so stop talking

#

?

slate swan
#

No I didnt, I had that saved from the Nextcord discord for when I asked that question.

iron sorrel
#

i mean, still that answer was bad, so please stop sending openai answers, but still

slate swan
iron sorrel
#

cap lol that is so cap

slate swan
#

And it wasnt bad, that is a very good way of doing it.

iron sorrel
#

no lol

tired coyote
#

can you all 3 shut the fuck up and go somewhere else this is a help channel not a argument channel

slate swan
iron sorrel
slate swan
#

that literally does not tell u how at all lmfao

iron sorrel
#

+1 literally

slate swan
#

Sigh I guess your blind.

slate swan
#

Well I didnt get it from there, I got it from the official Nextcord server when I asked that same exact question.

iron sorrel
iron sorrel
fading marlin
#

Let's say I've got a simple command that creates a persistent view

@bot.tree.command()
async def persistent(interaction: discord.Interaction, verify: discord.Role) -> None:
    await interaction.response.send_message(MyPersistentView(interaction.guild, verify.id))

now let's define our view. For the sake of simplicity it's only gonna have 1 button

class MyPersistentView(discord.ui.View):
    def __init__(self, guild: discord.Guild, role: int):
        self.role: int = role
        self.callback.custom_id = f"verify-callback:{guild.id}"
        #  Save the guild ID and role ID in your database

    @discord.ui.button(label="Get a role!")
    async def callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.user.add_roles(discord.Object(id=self.role))

Great! Now we have our view, and our command. Now we also have to add the view so it stays persistent

@bot.event
async def setup_hook():
    for row in database:
        for guild_id, role_id in row:
            bot.add_view(MyPersistentView(discord.Object(id=guild_id), role_id))

Ta-da! Now you've got a persistent view that works across multiple guilds

iron sorrel
#

thank you ^ actually useful

fading marlin
#

I'm proving syfe's point lol

slate swan
#

Exactly.

iron sorrel
#

but i asked my questions, jay gave official doc link, most useful, no need to keep going about this :D

tired coyote
slate swan
#

lmao

tired coyote
#

it's literally 1 view no need for a db

fading marlin
iron sorrel
slate swan
#

You never said if it was for one guild or not.

tired coyote
iron sorrel
slate swan
#

even if it's not one guild you still do not need this?

tired coyote
#

^^

slate swan
#

your doing what discord already does?

iron sorrel
fading marlin
#

🀷 There are multiple ways to code exactly the same thing, do as you like and don't start calling people "misinformant" just because you don't like their method

iron sorrel
slate swan
#

oh really? so telling someone they NEED a db to make a persistent view isn't misinforming? lmfao

fading marlin
#

I'm just providing a solution that I'm familiar with to a problem, there's no misinformation in that

iron sorrel
rare echo
#

tf goin on in here

#

this a grade school argument right here

slate swan
#

nah we got someone in here pasting other peoples code and chatGPT answers to peoples questions

fading marlin
fading marlin
#

I'm not gonna argue if syfe was misinformative or not, I'm just saying that there's a method to create persistent views in which you can use a database

rare echo
iron sorrel
#

^^^

iron sorrel
#

but ALL i needed was to add

@discord.ui.button(label="Verify", style=discord.ButtonStyle.green, custom_id="persistent_view:green")
#                                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#

and then self.add_view in setup_hook

#

but thanks to everyone who helped !

fading marlin
#

I'm glad you could solve your issue

jaunty sparrow
# slate swan the fucking button itselfs u moron

@slate swan there's no excuse to calling people names. If you have an issue with another member, you involve the moderators. Next time I'm just going to mute you.

@slate swan If you used ChatGPT or other AI tools to generate this answer, you need to stop. It was confusing and not very helpful in the context of the question.

slate swan
#

Im not, I've already said many times I got this answer from the Official Nextcord server when I asked that exact question.

#

thanks. he is also pasting other people's code from this discord itself and asking why it doesn't work. ima just block him as he is trolling at this point

#

Fine with me.

iron sorrel
#
@bot.command()
@commands.is_owner()
async def prepare(ctx: commands.Context):
    """Starts a persistent view."""
    # In order for a persistent view to be listened to, it needs to be sent to an actual message.
    # Call this method once just to store it somewhere.
    # In a more complicated program you might fetch the message_id from a database for use later.
    # However this is outside of the scope of this simple example.
    await ctx.send("What's your favourite colour?", view=PersistentView())
slate swan
#

another chatGPT answer he needs to be muted.

iron sorrel
#

you can as use a database as well, as listen in the official doc

slate swan
#

Hows that chatgpt?

iron sorrel
#

definitely openai

slate swan
#

?

iron sorrel
#

!e

# message id 1066070844352254012
start = 1674241495
# 1066070287239622797
end = 1674241363

print(start - end)  # 120
unkempt canyonBOT
#

@iron sorrel :white_check_mark: Your 3.11 eval job has completed with return code 0.

132
slate swan
#

im guessing if the bot doesn't already have access to the message itself?

#

it would need to fetch it

iron sorrel
#

!e

text = """
There are a few issues with this code:

1. There are multiple imports with the same name, such as from tkinter import Button and from discord.ui import Button. This can lead to confusion and errors when trying to use the imported module.

2. Some of the imports are not used in the code and are unnecessary, such as from code import interact, from cProfile import label, from operator import ne, from traceback import format_exception, from unicodedata import category, from webbrowser import BackgroundBrowser, from nturl2path import url2pathname, from PIL import Image, ImageDraw, ImageFont.

3. Some of the imports are not compatible with the discord library, such as import numpy as np, import requests, from PIL import Image, ImageDraw, ImageFont. These libraries are not designed to work with discord and will likely cause issues if used with discord.

4.There is no code that uses these imports, this imports are just taking space and are not doing anything.
I would recommend removing any unused imports, and double-checking that any imports that are used are compatible with the discord library.

Additionally, the imports should be grouped in a logical way, for example, all the discord imports should be together and all the standard library imports should be together.
"""
print(len(text.split()) / 2.1)
unkempt canyonBOT
#

@iron sorrel :white_check_mark: Your 3.11 eval job has completed with return code 0.

97.14285714285714
iron sorrel
#

97 words per minute + formatting, you really are trying to hide the fact that its openai?

slate swan
simple plume
#

Hi!

slate swan
#

yo

simple plume
iron sorrel
#

hi venom

simple plume
#

So i have this code and the bot does not assume the command

iron sorrel
iron sorrel
#

yes

#

you need that intent to be enabled, on discord + inside your bot's code in order to receive the message's content

simple plume
#

I'm new to programming xD

iron sorrel
unkempt canyonBOT
#

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.

slate swan
#
print('Hello world!')
slate swan
#

thanks

simple plume
unkempt canyonBOT
#

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.

simple plume
cold sonnet
simple plume
cold sonnet
#

we know 3 things:
you got something
we don't know what you got
what you got doesn't work

cold sonnet
#

and you get an error about intents don't you

simple plume
cold sonnet
#

and I don't know why