#discord-bots

1 messages · Page 92 of 1

untold iron
#

When i was meant to reference another function lol my mistake, effectively made an infinite loop

feral frost
#

ahhaha ye i had that once too

faint sapphire
#

hi
i get the locked error
I implemented: ```py
bot = commands.Bot(command_prefix='', intents=intents)
bot.db_con = None

@bot.event
async def on_ready():
if bot.db_con is None:
bot.db_con = bot.db_con = await aiosqlite.connect("cvb.db")

tho still getting the error
apparently this can help but idk how to integrate `int sqlite3_busy_timeout(sqlite3*, int ms);`

the two functions using the db and the task loop: https://paste.pythondiscord.com/uvapiyuher 
(note: I try make it do 2 `executemany` with 600+ tuples each)
wanton pebble
#

anyone know the nextcord way to do avatar_url_as? i cant do avatar.url cuz i need the actual image for pillow 😔

#

yeah that gives the link but cuz pillow is an image library it only accepts images and idk how to make it turn a url into an image

feral frost
#

ye i misread that

wanton pebble
#

lol

#

thanks though

feral frost
#
async def info(ctx, user: discord.Member = None):

    img = Image.open("black.png")

    disc = user.discriminator

    id = user.id
    with open("users.json", "r") as f:
        users = json.load(f)
    lvl = users[str(id)]["level"]

    asset = user.avatar_url_as(size=256)
    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    img.paste(pfp, (60, 30))

    draw = ImageDraw.Draw(img)
    font_medium = ImageFont.truetype("arial.ttf", 60)
    font_small = ImageFont.truetype("arial.ttf", 40)
    font_large = ImageFont.truetype("arial.ttf", 80)

    text = "Name:"
    draw.text((360, 45), text, (255, 255, 255), font=font_small)

    text = f"{user.name}"
    draw.text((500, 30), text, (82, 100, 196), font=font_medium)

    text = "Level:"
    draw.text((360, 135), text, (255, 255, 255), font=font_small)

    text = f"{lvl}"
    draw.text((500, 120), text, (82, 100, 196), font=font_medium)

    img.save("nice2.png")

    await ctx.send(file=discord.File("nice2.png"))``` my pillow avatar thing
feral frost
#

i use asset = user.avatar_url_as(size=256)

#

and some more under it

wanton pebble
#

it says member has no attribute avatar_url_as

feral frost
#

hmm

wanton pebble
#

you're using nextcord or a different fork?

feral frost
#

idk

#

idk what i use how do i check ?

wanton pebble
#

did you say import discord?

#

or import nextcord

feral frost
#

discord

wanton pebble
#

yeah nextcord is different

feral frost
#

ah ok

wanton pebble
#

thanks for trying though

grizzled badger
#

anyone got ideas for a fun and simple thing for a random bot (im noob coder btw)

grizzled badger
#

hmm

grizzled badger
wanton pebble
#

i used an RPG cog to get myself started when I was first learning discord.py lol

grizzled badger
#

i can umm reply to message

wanton pebble
#

o

grizzled badger
#

and just learn how to ping ppl lol

wanton pebble
#

hmmm how about 8ball?

grizzled badger
#

good idea

#

ty

wanton pebble
#

np

feral frost
#

also make a nice help command

#

use buttons or select and emojis to make it epic

wanton pebble
#

he dosent know much so interactions might be a bit far

#

for the moment^

feral frost
#

its easy to learn

wanton pebble
#

but thats a good idea for a bit later on

feral frost
#

ok

wanton pebble
feral frost
#

begin with a simple one then

#

embed

wanton pebble
#

very true

feral frost
#

no embed in help command = trash

primal token
grizzled badger
#

hmm yes sounds very simple

grizzled badger
primal token
primal token
#

I've never seen it done in a discord bot and would be quite unique and cool to see

grizzled badger
#

but everything else? nope

#

i just learnt how to mention a user

#

and you want me to make a whole interpreter XD

primal token
# grizzled badger but everything else? nope

Just take an unknown amount of arguments being your code, and then pass it into a parser function that parses the given code and returns a result, e.g /summon ender_dragon returns the name of the mob and then you use an api to get an img of the mob, parse the payload and send an embed with an img of the mob saying it was summoned

grizzled badger
#

and i have no idea how to do that

#

im new to discord python XD

faint sapphire
#

this causes sqlite lock
do i add a asyncio.sleep?```py
if len(updatedInfoSv) >= 1:
sqlSv = '''INSERT INTO itemsInfo(name, sv_value, sv_demand, sv_rarity, sv_stability, sv_status, sv_opUpRange, class) VALUES(?,?,?,?,?,?,?,?)ON CONFLICT(name) DO UPDATE SET sv_value = excluded.sv_value, sv_demand = excluded.sv_demand, sv_rarity = excluded.sv_rarity, sv_stability = excluded.sv_stability, sv_status = excluded.sv_status, sv_opUpRange = excluded.sv_opUpRange'''
await cur.executemany(sqlSv, updatedInfoSv)
if svUpdate == None:
svUpdate = await lastUpdate("sv")

if len(updatedInfoMv) >= 1:
sqlMv = '''INSERT INTO itemsInfo(name, mv_value, mv_demand, mv_rarity, mv_stability, mv_status, sv_opUpRange) VALUES(?,?,?,?,?,?,?)ON CONFLICT(name) DO UPDATE SET mv_value = excluded.mv_value, mv_demand = excluded.mv_demand, mv_rarity = excluded.mv_rarity, mv_stability = excluded.mv_stability, mv_status = excluded.mv_status, mv_opUpRange = excluded.mv_opUpRange'''
await cur.executemany(sqlMv, updatedInfoMv)
if mvUpdate == None:
mvUpdate = await lastUpdate("mv")

primal token
lapis cedar
#

pycord or discord py guys?

#

or is there another I should try

primal token
grizzled badger
wanton pebble
primal token
#

There's hikari, discord.py, disnake and much others

wanton pebble
#

@primal token you know any nextcord?

lapis cedar
#

In fact it doesn’t really have to be robust, just modern/easy to work with preferably

#

good docs etc

faint sapphire
wanton pebble
#

iirc both stay upto date

primal token
# lapis cedar good docs etc

If you're interested in something good and new hikari would be your choice, if you want the same abstractions as discord.py but has its old codebase your choice would be forks, i would prefer disnake as its abstractions are quite good and the library is up to date

patent wagon
#

how do i self host a bot

lapis cedar
#

Thanks for the suggestions guys

patent wagon
#

do i run it in some edditor

wanton pebble
patent wagon
#

or in .exe

patent wagon
wanton pebble
patent wagon
#

are there any usefull tips?

wanton pebble
#

good question but idk i just use a server

primal token
primal token
wanton pebble
#

noid you know nextcord?

unkempt canyonBOT
wanton pebble
# patent wagon tnx

random fact but you joined this server exactly a year after your account was made

primal token
wanton pebble
#

rip

primal token
wanton pebble
#

amazing

faint sapphire
#

anyone uses Postgres or MySQL

#

ig i have to switch

#

aiosqlite keeps getting database lock

primal token
wanton pebble
primal token
#

They dont take 1 hour to register globally but that isnt due to the library but its due to the new discord REST API update that makes registering app commands almost instant

wanton pebble
primal token
#

That would depend on the bots codebase, yes, maybe your wifi is just slow

wanton pebble
#

my wifi is usually between 400-700mbps Aqua_cry_FB

#

but you did just give me an idea to solve my issue

mental hollow
#

How can I make a slash command option take a discord.Emoji?

faint sapphire
#

fr i didnt understand

#

does it work to use Postgres for a discord bot

sick birch
untold iron
#

Hey there i have a simple create channel command, however how can i make it so it automatically makes the user go to the channel once it is created?

#

I want it so the user doesnt need to click on the new channel, it just places them in the channel automatically

sick birch
untold iron
#

Ah, understood. However how does the ticket tool do it, whenever a new ticket is made the user is automatically placed in the new channel

sick birch
#

I don't know what tool you're talking about but it's not possible

#

unless it like deletes the current channel or some weird workaround to force the client to switch channels

faint sapphire
#

lol

formal olive
#

Hi guys just wanna know if it's possible to make a stack exchange discord bot that tracks the reputation and question answered.

maiden fable
#

If stack has an API, then why not

patent wagon
#

how to add a delay on a function

wanton pebble
patent wagon
#

o

#

fair enough

wanton pebble
#

robin if you see this msg could you ping me? ty

#

i require your 9000iq

faint sapphire
#

is this ok for a requirements file?

wanton pebble
#

although i recommend adding versions

faint sapphire
#

pip3 freeze > requirements.txt

primal token
faint sapphire
#

ok thanks

slate swan
#

why is this an error??

weary flume
#

my bot was working fine until a day or two ago

#
    for guild in client.guilds:
        await guild.ban(user)
        print("here")
#

wont get past this

patent wagon
wanton pebble
patent wagon
#

but

#

do i just put it on the end?

wanton pebble
#

put it where ever you want it to wait a bit lmao

patent wagon
patent wagon
slate swan
#

how do i fix this

oblique loom
#
  File "C:\Users\Travis\PycharmProjects\MainAttempts\PikleDiscordBot.py", line 28, in <module>
    bot.run(DISCORD_TOKEN)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Users\Travis\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Travis\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 745, in start
    await self.login(token)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 577, in login
    raise TypeError(f'expected token to be a str, received {token.__class__!r} instead')
TypeError: expected token to be a str, received <class 'NoneType'> instead```
#

please help

#

i keep getting this

patent wagon
#

did u put it in " "

oblique loom
#

os.getenv("Insert token here", default=None)

patent wagon
#

use os.evniron(['DISCORD_TOKEN'])

slate swan
#

someone help me fix this pls

patent wagon
#

not ==

patent wagon
wanton pebble
patent wagon
oblique loom
primal token
patent wagon
#

o

#

my bad

#

try this:

oblique loom
#

no im using pycharm, is that ok?

patent wagon
#

yes

patent wagon
#

my bad it isnt os.environ(['TOKEN])

slate swan
#
    with open('prefix.json', 'r') as f:
        prefixes = json.load(f)

    return prefixes[str(message.guild.id)]

@client.event
async def on_guild_join(guild):
    with open('prefix.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = ','

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefix.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop[str(guild.id)] = ','

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.command(aliases=['prefix'])
async def setprefix(ctx, prefixset = None):
    if (not ctx.author.guild_premissions.manage_channels):
        await ctx.send("You're **missing** permission: ``manage_channels`` ")
        return

    if (prefix.set == None):
        prefixset = ','

        prefixes = json.load(f)

        prefixes[str(ctx.guild.id)] = prefix.set

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)

        await ctx.send(f"The bot prefix has been changed to ``{prefixset}``")``` **This is the code can someone help me fix the error?**
oblique loom
#
from discord.ext import commands
import pygame
import pyautogui
import os
from discord import Intents

token = os.environ[token here']
intents = Intents.default()
intents.members = True


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

@bot.command()
async def ping(ctx):
    await ctx.channel.send("pong")


@bot.command()
async def print(ctx, arg):
    await ctx.channel.send(arg)


bot.run(token)```

this is my code, what do i have wrong
oblique loom
#

@patent wagon i have to go, ill message you about this later, thanks tho

slate swan
#

Alright, I send a get request to the API then I need to fliter the json response and get the ID and then send a new get request with the ID it go

rapid knoll
#

how do I send private messages using the discord bot?

mental hollow
rapid knoll
slate swan
#

Alright, I send a get request to the API then I need to fliter the json response and get the ID and then send a new get request with the ID it go

mental hollow
mossy jacinth
#

please someone help me

bold kernel
#

Hi, how can I use "for" iteration on discord bot like for this purpose : ```@client.hybrid_command(name = "testing", with_app_command = True, description = "Testing", )
@app_commands.guilds(discord.Object(id = guild_id))
async def testing(ctx: commands.Context, content, channel: discord.TextChannel):
channels_send.append(channel.id)
contents_send.append(content)
await ctx.send("ok", delete_after=3)

@client.command()
async def program(ctx):
for channel_send in channels_send:
channel = client.get_channel(channel_send)
print(channel)
for content_send in contents_send:
await channel.send(content_send)```?

slate swan
#

Hola

#

@quaint epoch me puedes ayudar con un bot?

#

Necesito que alguien me ayude con un bot que usa java script
(Mencioname si me puedes ayudar por favor)

sick birch
#

@upper glacier please use english to the best of your ability

slate swan
#
@bot.command
@lightbulb.option("my_arg", "my_desc")
@lightbulb.command("my_cmd","my_desc")
@lightbulb.implements(lightbulb.SlashCommand)

How would i make my_arg only accept an integer?

quaint epoch
unkempt canyonBOT
#

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

slate swan
#

Alright, I send a get request to the API then I need to fliter the json response and get the ID and then send a new get request with the ID it got

#

how do i do that

fading marlin
patent wagon
#

what do i do in case someone steals my discord bot token

rare echo
patent wagon
rare echo
patent wagon
#

is there any way i can save token in a locked file

rare echo
#

wait

patent wagon
#

or someting

rare echo
#

if they are hosting it then they somehow need to connect to the bot

patent wagon
#

exactly

rare echo
#

so not that im aware of

#

either way, your bots token or theirs they'll have full access to the bot

patent wagon
#

they wont have my discord dev portal

#

they will ahve the code and the token

rare echo
#

well... yes

patent wagon
#

can they log in discord dev protal with my bots token?

rare echo
#

no not what i was saying

fading marlin
rare echo
#

whats stopping you from hosting?

#

/ what are they providing you cant get yourself

patent wagon
#

they are hosting an minecraft server and have a bunch of space

#

and proper eqiipment

rare echo
#

i mean.. equipment is a bit of a stretch

#

if its a smaller bot, you can host online for a very small cost

patent wagon
#

like lets say they want to use my bot for malicious puropse i could in theory delete the bot in deiscord dev portal and stop them right?

rare echo
#

yes but thats not to say it wont nuke your server / ruin what you are doing before you have time to sign in and regenerate

patent wagon
#

its not run on my server

#

its run on theirs

sick birch
#

if you're giving your bot files for someone else to host you better trust them 200%

patent wagon
#

im trusting them 90%

sick birch
#

Then I wouldn't give it to them

patent wagon
#

bro it will be run on their server

sick birch
#

I trust companies like AWS, GCP, MS Azure, Oracle 200%, I'll host my bot with them

#

You may want to consider looking into a few of those

patent wagon
#

how much per month

rare echo
sick birch
#

It varies widely

rare echo
patent wagon
sick birch
#

If you've got any old hardware lying around that's very good

patent wagon
sick birch
#

I don't sell anything

patent wagon
sick birch
#

Great, install linux on it and run a bot. Should be more than enough

patent wagon
rare echo
sick birch
#

Lightweight, more resources for your bot instead of bloating yourself with windows with stuff you don't need

#

don't even need a DE just pop on ubuntu server edition and you're golden

#

I personally use AWS for hosting my bot and it's dashboard, and a few other components needed to make the bot run. I could've probably done it on my raspberry pi, but I wanted to learn DevOps :p

patent wagon
#

i have 0 expirience with linux

#

what bout running it in idle?

#

or someting

rare echo
sick birch
patent wagon
#

il give it a try

#

im yet to try heroku

sick birch
#

Good, keep it that way

patent wagon
#

i heard they are soon removing some free features

#

will they effect the functionality of a bot?

sick birch
#

well yeah you'll have to start paying

patent wagon
rare echo
#

i.e an old pc, localhost, pi etc

slate swan
#

Why is this an error?

patent wagon
#

chanel?

slate swan
rare echo
#

or taken from something

slate swan
rare echo
#

potentially different in your case ^ but i cant see the rest

rare echo
#

can you show more?

#

like the whole cmd

slate swan
rare echo
#

try context.channel.mention

#

ctx is usually a shorter form of that

slate swan
kindred epoch
#

how do i turn a discord timestamp into seconds?

rare echo
kindred epoch
#

nvm

flint dome
#

how could i check fi someone sent there msg via dm or guild in d.py

sick birch
primal token
#

!d discord.Message.guild

unkempt canyonBOT
sick birch
#

though there is a @guild_only check if that's what you're looking for

rare echo
primal token
#

?

slate swan
#

How do i send a message to a specific channel

#

channel = bot.get_channel()
await channel.send('hello')

#

then it only sends the first word

weak quail
slate swan
#

but it only sends the first word

weak quail
#

wym? 'hello' is one word

weak quail
slate swan
#

channel = bot.get_channel(channel_id)
await channel.send('hello friend')

#

@weak quail ^

weak quail
#

do you want it to only send the first word? or..?

slate swan
#

The whole thing

#

but it only sends the first word

#

@weak quail

weak quail
#

your code should work as expected

weak quail
slate swan
slate swan
#

Is there an event for when the forum channel is closed by the author and can I reopen it?

slate swan
#

Thanks! I has another question, The close post option in threads, does it archive the thread?

hollow agate
#

Then, you filter py thread = interaction.channel if interaction.user == thread.owner: and use await thread.edit(locked=False, archived=False)

slate swan
hollow agate
#

Yep

slate swan
#

But I can still message in it? Archived posts I cant message in?

#

Oh wait never mind

#

I think I got it wrong, thanks for the help

hollow agate
#

No worries

scarlet sorrel
#

How do i take something like a user object and print all the information it holds as a string or something? Like how you can do print(message) and it gives you everything, how do you do that for a user object?

nimble acorn
scarlet sorrel
#

Repr() gets some but it does not get stuff like guild.icon_url

nimble acorn
#

you can just make a function and print the attributes out accordingly though

scarlet sorrel
nimble acorn
#

use isinstance() to check then

scarlet sorrel
#

Then i still have to write out every single check for every type of object tho

#

Which i have already done

#

Gotta be a better way tho

nimble acorn
#

hmm then im not sure about it

#

i dont think this is the problem but you should break the while loop or return the function

stable crown
#

i was making a pokemon bot and had to like use the pokemon emojis but there are like 800 pokemon 😔 should i just make the bot upload an emoji whenever it needs it and then delete it?

nimble acorn
#

the while True one, if you dont break it or return it, it will keep waiting for a new number and the game wont end

#

o then its not the problem 🤔

shrewd apex
scarlet sorrel
#

'User' object has no attribute 'banner' ????

shrewd apex
#

just start with gen1 and add emojis later once bot is verified

scarlet sorrel
#

Im looking at the docs and it says property banner Returns the user’s banner asset, if available.

torn sail
#

!d discord.User.banner

unkempt canyonBOT
#

property banner```
Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
scarlet sorrel
#

New in version 2.0.

#

How do i get version 2.0

#

Or do i just need to update it

#

?

sly fog
#

how do I edit the content of a button

slate swan
#

hello

#

anyone is here i needed some help regarding my bot

rare echo
slate swan
#

import discord
ModuleNotFoundError: No module named 'discord'

#

Any solution to this?

#

I tried pip install discord and python -m pip install discord both

#

just ping me if anyone can help

rare echo
slate swan
#

no im running on VS-Code

#

python 3.9.6

jagged adder
#

whats the correct discord.py term for gathering all messages in a channel? ik fetch_message is for a single one. I want my bot to add 👍 👎 emojis to all messages in a specific channel.
I just need the correct words so i can look it up on the docs (theres something like 100+ results when i just search 'message')

rare echo
jagged adder
#

yeah but i want to add the emojis to every past msg too

#

i need a way to fetch the ids of all the msgs in said channel and use a for loop

#

itll be a once off; after this ill just remove that piece of code from the bot and use my existing on_message one that adds the emojis upon creation

slate swan
unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

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

Examples

Usage...
jagged adder
#

ahh

#

that looks promising

slate swan
#

hello

slate swan
#

we can't work without no errors. do you have an error handler?

swift pumice
#

german moment

slate swan
#

do you have an error handler or not?

#

hm yeh

bold kernel
slate swan
bold kernel
slate swan
bold kernel
scarlet sorrel
slate swan
#

dunno then

#

idk then

scarlet sorrel
#

How?

slate swan
scarlet sorrel
#

Successfully installed discord.py-1.7.3

#

Cuh

slate swan
#

did they remove the release or what lol

#

no it's 2.0.1

#

try doing

pip install discord.py==2.0.1```
scarlet sorrel
#

ERROR: Could not find a version that satisfies the requirement discord.py-2.0.1 (from versions: none)
ERROR: No matching distribution found for discord.py-2.0.1

scarlet sorrel
slate swan
#

lmao

bold kernel
slate swan
#

I already edited that

scarlet sorrel
#
ERROR: Ignored the following versions that require a different python version: 2.0.0 Requires-Python >=3.8.0; 2.0.1 Requires-Python >=3.8.0
ERROR: Could not find a version that satisfies the requirement discord.py==2.0.1 (from versions: 0.1.0, 0.2.0, 0.2.1, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.7.0, 0.8.0, 0.9.0, 0.9.1, 0.9.2, 0.10.0, 0.11.0, 0.12.0, 0.13.0, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.16.7, 0.16.8, 0.16.9, 0.16.10, 0.16.11, 0.16.12, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3)
ERROR: No matching distribution found for discord.py==2.0.1
slate swan
scarlet sorrel
#

How do i update python

scarlet sorrel
slate swan
#

where do you expect

scarlet sorrel
#

No this is AWS

#

Cant just go to a website

slate swan
#

nice

scarlet sorrel
#

And i forget how to do it

slate swan
#

sarthy 😳

scarlet sorrel
#

I did it like a year ago

#

No clue

bold kernel
# slate swan loop through `dict.items`

dict={channel1.id : content1, channel2.id : content2}for example and so i need to do

             channel = client.get_channel(item)
await channel.send(item)```
Is it like this ?
slate swan
slate swan
scarlet sorrel
#

Alr sarthy

slate swan
#

sarthy

#

stop calling him that 😔

slate swan
#

!d dict.items

unkempt canyonBOT
#

items()```
Return a new view of the dictionary’s items (`(key, value)` pairs). See the [documentation of view objects](https://docs.python.org/3/library/stdtypes.html#dict-views).
scarlet sorrel
slate swan
#

smh

scarlet sorrel
#

🥺

bold kernel
scarlet sorrel
#

@slate swan you seem like a very intelligent person, do you by any chance know how to get all the info for an object, say i had a command that accepts any id, be it a guild id or message id or user id and the command tries to return as much info as it can get from that id, how do i do that, because stuff like repr() only gets a little bit, like if it was a guild id it wouldn't get the guild.icon_url or anything like that.

right now i just have a ton of try and excepts to try and get every attribute of every possible object

slate swan
slate swan
#

if it is not a valid id , an error would be raised and you can move on to the next object to convert

#

!d discord.ext.commands.MemberConverter.convert

unkempt canyonBOT
#

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

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
slate swan
#

!d discord.ext.commands.GuildConverter

unkempt canyonBOT
#

class discord.ext.commands.GuildConverter(*args, **kwargs)```
Converts to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

The lookup strategy is as follows (in order):

1. Lookup by ID.

2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names).

New in version 1.7.
slate swan
slate swan
#

ahh thanks

heavy folio
#

Adding and removing users from a thread:
so to check if a member is in a thread i did ```py
if thread.permissions_for(member).view_channel:
raise BadArgument('They are already in this thread...')

however it seems like it doesnt work since they can view the thread even after i called `thread.remove_user()`, but just not type
is there an alternative?

also another problem is after i call `remove_user()` on them, doing `add_user()` does nothing, they're still "cancelled" from thread  and cannot type anything
scarlet sorrel
slate swan
#
            channel = await self.bot.fetch_channel(int(payload.data["id"]))
            print(channel.archiver_id)

This returns none?
The channel is archived and printing the channel.id does return the channel id

glad cradle
#

you can send only 1 view per message, though 1 view could contain multiple components

slate swan
#

Only the archiver_id isnt returned..

glad cradle
#

what's the type of the channel

slate swan
glad cradle
#

there's no archiver_id attribute/property for discord.ForumChannel, do you mean discord.ForumChannel.archived_threads?

slate swan
glad cradle
#

true

#

was the thread archived by someone or it was automatically archived for inactivity?

glad cradle
#

should work

slate swan
#
    @commands.Cog.listener(name="on_raw_thread_update")
    async def forum_channel_archived(self, payload):
        data = payload.data
        if (
            data["thread_metadata"]["archived"] == True
            and data["parent_id"] == "1019806662766379160"
        ):
            channel = await self.bot.fetch_channel(int(payload.data["id"]))
            if channel.archiver_id == int(data["owner_id"]):
                await channel.edit(archived=False)
                await channel.send(
                    "You cannot archive your own thread. It has been unarchived and will be automatically archived after 1 hour of inactivity."
                )
#

Thats my whole code

glad cradle
#

I'm not sure but could be that the fetched thread is not a full thread object?

slate swan
#

Yeah thats what I thought, trying get_channel_or_thread now

#

The problem is my thread is alr archived

#

And yes I am on dpy2

glad cradle
#

so you should use a discord.Guild obj

slate swan
#

oh

glad cradle
#

btw if I'm correct this will not resolve your issue

glad cradle
slate swan
#

The event is triggered

#

I have tried everything.. this close to giving up

novel geyser
#

This line does not work. Everything else works fine. No errors either

glad cradle
glad cradle
novel geyser
#

print(r) prints nothing which is weird

novel geyser
#

prints nothing @glad cradle

glad cradle
novel geyser
#

Nothing

glad cradle
#

then the else block is not triggered

novel geyser
#

It is. Because the reaction gets removed

glad cradle
#

or the emoji is not equal to what you're checking

novel geyser
#

Should be

glad cradle
slate swan
novel geyser
#

Won't even print the test

glad cradle
glad cradle
novel geyser
#

Yes

#

Just changed to this to see if the else statements were fucking it up. Still nothing

glad cradle
novel geyser
#

This is in the main.py file, only other ones would probably be in cogs which shouldn't matter

#

But no there's nothing else in the main file

naive briar
novel geyser
#

The event should be being triggered. The reaction gets removed, But I can try

#

Ok now I'm officially confused. Not printing still...

naive briar
novel geyser
#

I've got all intents

naive briar
novel geyser
#

ima try putting this in a cog and see if it changes

novel geyser
#

@naive briar Still doesn't work in the cog

glad cradle
#

are you removing a reaction in the on_raw_reaction_add that's in your cog?

novel geyser
#

I even disabled the line where it removes the reaction and it still removes my reaction

#

This is so weird

glad cradle
#

that's coz you have another on_raw_reaction_add in your Bot that removes a reaction

slate swan
novel geyser
#

Ok I fixed it. But no, that shouldn't have been the issue

novel geyser
#

ty guys for the help

rapid knoll
#

My discord bot is refusing to work, all the code is correct and the bot turns on but the bot will not respond to its prefix

glad cradle
#

is it verified?

rapid knoll
#

no?

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

naive briar
#

The intent message_content could be missing pithink

robust fulcrum
#

This not worked

embed1.set_image(url="attachment://sprites/mouse.jpg")
slate swan
#

I mean, other directories

slate swan
#

it has to be in the root dir else there's no point.

naive briar
rapid knoll
#

How do I check on what someone has reacted with?

slate swan
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
naive briar
#

The discord.ui.button decorator shouldn't be there

#

Or you can pass it to get back to edit it later

@discord.ui.button(...)
async def vote(...):
    pass
scarlet sorrel
slate swan
#

guys I need help

#

I got an error

nextcord.ext.commands.errors.CommandNotFound: Command "balance" is not found```
#

I was trying to do economy bot

slate swan
unkempt canyonBOT
slate swan
#

!d discord.Asset.url

unkempt canyonBOT
scarlet sorrel
#

Im using guild.icon_url in my code and it returns the url

slate swan
#

how to add nd button?

#

are you on 1.7.3?

#

please help

scarlet sorrel
#

I updated then vomited when i saw you can't start a client with a user token and went back to 1.7.3

slate swan
#

oh

#

Please help

scarlet sorrel
#

Check ur intents

#

You need messages

#

Because you are trying to see message content

slate swan
scarlet sorrel
#

You what

#

You dont need an application cuh

#

You just need to add messages to your intents

#

No you don't

#

Just add it the exact same as the other intent

#

Just add it the exact same as the other intent

#

You said you already had an intent

#

That aint an intent cuh

#

Ask someone else im busy af

wise wind
#

anyone know how to fix


    for url2, price in data1.items():
RuntimeError: dictionary changed size during iteration```

happens when im doing `!remove` command which is

```    data.pop(url)
    data1.pop(url2)```
#

ping me if you answer to this pls

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://discordapp.com/developers/applications/me

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

slate swan
#

anyone can help me?

import discord; from discord.ext import commands
bot = discord.Bot(command_prefix='$', activity="asd", status=discord.Status.online, intents=discord.Intents.all())
@bot.command(name="payments")
async def p(a):
    await a.send(embed=discord.Embed(title="payments below").add_field(name="paypal", value="yourpp@domain").add_field(name="ltc", value="addy"))
bot.run('bot token')
glad cradle
primal token
glad cradle
primal token
#

It's still a thing lol

glad cradle
#

if he's using discord.py it's not a thing that package

primal token
#

You never specified it wasnt a thing in the discord.py library

robust fulcrum
#

Guys i have a bot.wait_for('message') in my slash command code
So how can I send message to comamnd user channel when someone sends message?

slate swan
#

And you do e = discord.embed(title="hi")
await send(embed=e)

slate swan
#

how to reply to a message?

honest shoal
unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
robust fulcrum
# honest shoal ?

?
I want to send message 2 times when someone my slash command but i not able to

honest shoal
#

Other one should be a normal msg

robust fulcrum
robust fulcrum
#

interaction.channel.send?

honest shoal
honest shoal
robust fulcrum
#

No i have a battle type i want to take input from user like type 1 for attack

honest shoal
#

I don't understand, but you can have it in slash commands too

robust fulcrum
# honest shoal I don't understand, but you can have it in slash commands too
    @app_commands.command(name="wild", description="start a wild battle.")
    async def _wild(self, interaction: discord.Interaction):
        user = await self.check(interaction.user.id)
        if user == False:
            await interaction.response.send_message("Ah! you have not started the game.\nPlease start by using `/start` command.")
        else:
            user_stats = await self.bot.stats.read(interaction.user.id)
            user_hp = self.hp(user_stats.hp,user_stats.hp)
            mouse_stats = self.mouse_stats()
            mouse_hp = self.hp(int(mouse_stats[0]),int(mouse_stats[0]))
            embed1 = Embed(
                title=interaction.user,
                description=f"**You**: {user_hp}\n```{user_stats.hp}/{user_stats.hp}```\n**Mouse**: {mouse_hp}\n```{mouse_stats[0]}/{mouse_stats[0]}```"
            )
            file = discord.File("sprites/mouse.jpg",filename="mouse.jpg")
            embed1.set_image(url="attachment://mouse.jpg")
            embed1.set_footer(text="Type `1` to attack,`2` to defend")
            original = await interaction.response.send_message(file=file,embed=embed1)
            alive = True
            while alive==True:
                mes = await self.bot.wait_for('message',check=self.mss)
                if mes.content == 1:
                    await interaction.channel.send("attack")
                elif mes.content == 2:
                    await interaction.channel.send("defenc")

When i send 1 my bot is not sending message
Do you know why?

honest shoal
#

What's the error

#

And why don't you use buttons

cloud dawn
onyx cipher
#

hello

#

does anyone know why this

#

its getting an error

#

it says that it doesnt recongize bot as a work or szmin

cloud dawn
#

Please provide the full error and a better view of the code.

slate swan
#

Command raised an exception: AttributeError: 'builtin_function_or_method' object has no attribute 'endswith'

#

you have any on_message event ?

#

oh you have to add 'await client.process_commands(message)' in the last of your on_message

#

it have to be the last thing in your event

robust fulcrum
#

What would be the check for the bot.wait_for in slash command?

limber bison
#

how u define def like verify n all ?

rotund leaf
#

Hey all.

faint sapphire
#

me wondering why i cant use a discord server to host my discord bot and use the channels to run code and as a database

#

im prob gonna use some channels as a db tho, unlimited storage

naive briar
#

What is the problem?

quaint epoch
#

The second one is plausible but not really

#

Wait nope

faint sapphire
faint sapphire
primal token
#

It's against TOS iirc

faint sapphire
#

uni friends of a friend of mine made use of channels as a db lol

#

idk specifics

#

for text its obviously dumb, unless if its just files
also for images it would make sense

onyx cipher
#

Can someone help ?

wanton pebble
glad cradle
# faint sapphire what does that mean

you need to make Api calls to fetch and send message (with the given example to read and write data), discord could rate limit the Bot depending on the requests made to read/write data

onyx cipher
wanton pebble
#

dont create selfbots

onyx cipher
primal token
#

Kiz did you noticed the bool he passed?

#

😭

wanton pebble
#

oh yeah, its the issue

#

he wants a selfbot but bot isnt an arg for that function since selfbots got deprecated

primal token
#

Yeah nvm, i thought he passed bot=True but i looked closer and it was False

wanton pebble
#

lmao

primal token
#

My vision is slowly deteorating

wanton pebble
#

old human im joking ily

glad cradle
#

eye issue

primal token
wanton pebble
wanton pebble
celest orbit
#

salut les amis

primal token
wanton pebble
#

lmaooo

primal token
#

bot.loop returns None

#

i'm pretty sure its an internal only attribute after 2.0 iirc

rotund creek
#

so I have a simple ban command

celest orbit
primal token
#

!d asyncio.get_event_loop

unkempt canyonBOT
#

asyncio.get_event_loop()```
Get the current event loop.

If there is no current event loop set in the current OS thread, the OS thread is main, and [`set_event_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.set_event_loop "asyncio.set_event_loop") has not yet been called, asyncio will create a new event loop and set it as the current one.

Because this function has rather complex behavior (especially when custom event loop policies are in use), using the [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop") function is preferred to [`get_event_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop "asyncio.get_event_loop") in coroutines and callbacks.

Consider also using the [`asyncio.run()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.run "asyncio.run") function instead of using lower level functions to manually create and close an event loop.

Deprecated since version 3.10: Deprecation warning is emitted if there is no running event loop. In future Python releases, this function will be an alias of [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop").
rotund creek
#

async def ban(ctx, member: discord.Member) how can I also allow this to accept an ID of the user

glad cradle
#

bot.pool return None

primal token
#

wait what

primal token
glad cradle
celest orbit
#

can you help me ?
I am a beginner in phthon

glad cradle
primal token
#

😦

glad cradle
celest orbit
#

How do I replace numbers with words?

primal token
glad cradle
rotund creek
glad cradle
#

or iirc with python >=3.9 you could just do member: discord.Member | int

primal token
rotund creek
#

when do member.ban()

primal token
#

You should annotate the member argument with discord.Member only as the converter can do object conversion if a snowflake is passed then you can use the method on the local variable

rotund creek
#

huh

glad cradle
primal token
glad cradle
#

take crack if it's too painful

primal token
#

⁉️

slate swan
#

hey guys anyone interested in helping me to add economy to my bot?

slate swan
#

Hi

#

So I want that if people will get a different role when the boost the server

#
for guild in bot.guilds:
        for member in guild.members:
            role = get(guild.roles, id ="1017155420550344808")
            if str(1017155420550344808) in str(member.roles):
                if str(member) not in booster["booster"]:
                    booster["booster"].append(str(member))
                    print(booster["booster"])
                    print(booster)
                    await member.add_roles(role)
                    with open("boosters.json", "w") as outfile:
                        outfile.write(json.dumps(booster, indent=4))
            else:
                if str(member) in booster["booster"]:
                    print(str(member))
                    booster["booster"].remove(str(member))
                    await member.remove_roles(role)
                    with open("boosters.json", "w") as outfile:
                        outfile.write(json.dumps(booster, indent=4))```
#

atm I have this

#

but it gives a error :/

maiden fable
#

role is None

weary flume
#
    for guild in client.guilds:
        await guild.ban(user, reason=reason)
#

not sure why this isnt working

slate swan
#

The id of premium is that

maiden fable
#

ids are int, not str

slate swan
slate swan
slate swan
#

error?

maiden fable
#

Is that a nuke bot 👀

weary flume
#

no

#

just easier to manage my servers

slate swan
weary flume
#

as soon as it gets to guild.ban it doesn't work

#

im confused bc it was working just fine like a few days ago

slate swan
#

well then the bot doesn't have perms to ban the user

#

or actually, the user is not in the server

weary flume
#

it has admin as soon as it joins servers tho

slate swan
#

or already banned

weary flume
#

so if its banned in even 1 of the servers it wont work?

maiden fable
#

U gotta use a try except

weary flume
#

can u show me?

limber bison
#

can i edit field at 1 ? in embeds ?

slate swan
maiden fable
#

!d discord.Guild.roles

unkempt canyonBOT
#

property roles```
Returns a sequence of the guild’s roles in hierarchy order.

The first element of this sequence will be the lowest role in the hierarchy.
slate swan
#

Still have no clue tbh

#

wait nvm

#

got it

primal token
# maiden fable ids are int, not str

Well, to be exact they are represented as snowflakes in discords documentation, snowflakes being unique ints, but yeah you arent wrong but you arent right either

maiden fable
#

Snowflakes are int, when talking in Python's context, so no idea why u think I am neither right

#

Weirddd

torn sail
#

You need make an instance of Warn. Right now you are just passing the class in. It should be Warn() not Warn

primal token
verbal ingot
glad cradle
#

!code

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.

verbal ingot
#

ohhhh

#

okiiii

#

thanks

novel apexBOT
#

This is not a Modmail thread.

primal token
glad cradle
buoyant linden
primal token
# buoyant linden

select is an interaction object, just switch around select and interaction

primal token
#

I ment in your functions parameters!

buoyant linden
#

Now I understand.

slate swan
#

how to make smth like this?

primal token
unkempt canyonBOT
slate swan
#

thamks

buoyant linden
#

The errror won't be gone.

#

Maybe I'm just stupid rn but here is the code if that's okay

Code:

class MySelect(View):

    @discord.ui.select(
        placeholder="Choose an option",
        options=[
            discord.SelectOption(label="Moderation", value="1", description="View the moderation commands."),
            discord.SelectOption(label="User", value="2", description="View the user commands."),
            discord.SelectOption(label="Music", value="3", description="View the music commands.")
        ]
    )

    async def select_callback(self, interaction, select):
        select.disabled=True
        if select.value[0] == '1':
            em = discord.Embed()
            em.add_field(title="RNG Moderation Commands", value="Comming Soon.", inline=False)
            await interaction.respose.send_message(embed=em)
        if select.value[0] == "2":
            em2 = discord.Embed()
            em2.add_field(title="RNG User Commands", value="Comming Soon.", inline=False)
            await interaction.response.send_message(embed=em2)
        if select.value[0] == "3":
            em3 = discord.Embed()
            em3.add_field(title="RNG Music Commnads", value="Comming Soon", inline=False)
slate swan
#

can i disable this label (Komendy:)?

honest shoal
honest shoal
#

oh I misread

slate swan
honest shoal
#

am sleepy, it's dropdown

slate swan
#

It's not here but maybe there is a way

honest shoal
#

afaik, you cannot disable a specific option in dropdown

slate swan
slate swan
wispy sequoia
#

how do I load extensions with discord.Client? I've always been using discord.ext.commands.Bot but I'm re-writing to slash commands so I use the client instead

primal token
wispy sequoia
#

yeah I read the docs

#

how am I supposed to use cogs then? I don't wanna write each and every command on 1 file

wispy sequoia
primal token
#

If you want Cogs and other abstractions, yes

wispy sequoia
#

k, thx

slate swan
#

and how can i turn custom_id into label to add a custom answer depending on what you click?

slate swan
#

where are you defining bot.pool?

weary flume
#
    for guild in client.guilds:
        await guild.ban(user, reason=reason)
#

anyone know whats wrong with this?

dull terrace
#

how's this looking 7739monkathink

primal token
primal token
#

Yes?

dull terrace
#

more padding between elements or?

oblique loom
#

someone please help

#
    bot = commands.Bot(command_prefix='$', activity="asd", status=discord.Status.online, intents=discord.Intents.all())
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\ext\commands\bot.py", line 171, in __init__
    super().__init__(intents=intents, **options)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\ext\commands\core.py", line 1265, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 253, in __init__
    self._connection: ConnectionState = self._get_state(intents=intents, **options)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 284, in _get_state
    return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\state.py", line 207, in __init__
    raise TypeError('activity parameter must derive from BaseActivity.')
TypeError: activity parameter must derive from BaseActivity. ```
#

this my error

#

@bot.command()
async def ping(ctx):
    await ctx.channel.send("pong")


@bot.command()
async def print(ctx, arg):
    await ctx.channel.send(arg)


bot.run('insert token here') ```
#

this my code

primal token
#

so its not so crowded

mental hollow
#

how do i check if a user is banned (for my user info command)?

slate swan
#
 # Move
    async def move(self) -> None:
        # Integers
        Y_INCREMENT, X_INCREMENT = self.TRANSLATIONS.get(self.direction, (0, 0))
        Y_HEAD, X_HEAD = self.head
        
        # Adjust tuples
        self.head = (Y_HEAD + Y_INCREMENT, X_HEAD + X_INCREMENT)
        
        # Loss detection
        if self.head in self.tail or self.head[0] < 0 or self.head[0] > self.COLUMNS - 1 or self.head[1] < 0 or self.head[0] > self.ROWS - 1:
            self.halt = True
            return None
        
        # Win detection
        if self.score == (self.COLUMNS * self.ROWS) - 1:
            self.halt = True
            return None
        
        # Tail management
        if len(self.tail) > 0:
            self.tail.pop()
            self.tail.insert(0, self.previous_head)
        
        # Apple eating
        if self.apple == self.head:
            self.generate_apple()
            self.tail.insert(0, self.previous_head)
            self.score += 1
        
        self.previous_head = self.head
        
        # Post
        await self.post(edit = True)
        
#

I made snake on discord, and I feel like some logic for the apple eating is messed up.

#

I'm not sure what, but it does not feel right at all.

oblique loom
#

@bot.command()
async def ping(ctx):
    await ctx.channel.send("pong")


@bot.command()
async def print(ctx, arg):
    await ctx.channel.send(arg)


bot.run('insert token here') ```

someone please help, this is my code that i have.

```File "C:\Users\Travis\PycharmProjects\MainAttempts\PikleDiscordBot.py", line 8, in <module>
    bot = commands.Bot(command_prefix='$', activity="asd", status=discord.Status.online, intents=discord.Intents.all())
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\ext\commands\bot.py", line 171, in __init__
    super().__init__(intents=intents, **options)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\ext\commands\core.py", line 1265, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 253, in __init__
    self._connection: ConnectionState = self._get_state(intents=intents, **options)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\client.py", line 284, in _get_state
    return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
  File "C:\Users\Travis\PycharmProjects\MainAttempts\venv\lib\site-packages\discord\state.py", line 207, in __init__
    raise TypeError('activity parameter must derive from BaseActivity.')
TypeError: activity parameter must derive from BaseActivity. ```

this is the error i keep getting
wicked atlas
#

activity can't be just a string, it needs to be some form of Activity object

#

For example

#

!d discord.Game

unkempt canyonBOT
#

class discord.Game(name, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity "discord.Activity") that represents a Discord game.

This is typically displayed via **Playing** on the official Discord client.

x == y Checks if two games are equal.

x != y Checks if two games are not equal.

hash(x) Returns the game’s hash.

str(x) Returns the game’s name.
wicked atlas
oblique loom
#

wait do i even need to put activity? or can i delete that?

#

i forgot i had it there

wicked atlas
#

It's not required

oblique loom
#

ok

#

thanks

#

oh yeah one more thing

#
async def ping(ctx):
    await ctx.channel.send("pong") ```

this sends a message in chat right? how would i make it send multiple times?
wicked atlas
#
 @bot.command()
async def ping(ctx):
    await ctx.channel.send("pong") 
    await ctx.channel.send("pong") 
    await ctx.channel.send("pong") 
    await ctx.channel.send("pong") 
    await ctx.channel.send("pong") 
    ...
oblique loom
#

thats it?

wicked atlas
#

You can call send as many times as you want in the function

oblique loom
#

damn ok.

#

thank you so much

slate swan
#

<button class="product-card__variant" data-variant="39253396095104" js-quick-add="" data-upsell="mens" aria-label="Add Variant">7</button>
how to retrieve the data variant?

oblique loom
primal token
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello World!
002 | Hello World!
003 | Hello World!
004 | Hello World!
005 | Hello World!
006 | Hello World!
slate swan
#

yas

tulip ice
#

why do u need to use the function names like on_message and not ur own function?

torn sail
upbeat gust
#

This also means you can only have one client.event for each even, as they overwrite eachother

radiant junco
queen cradle
#

Could someone help me with a project that I have on discord to create a bot for betting coins, games, among others, I need to help, thank you very much
I need someone who has ideas to be able to help me better

narrow cradle
#
-Traceback (most recent call last):
-  File "main.py", line 4, in <module>
-    client = discord.Client()
-TypeError: __init__() missing 1 required keyword-only argument: 'intents'

i get this error
i can show the code

sick birch
narrow cradle
#
intents = discord.Intents.default()
intents.typing = False
intents.presences = False

do i just use that

light violet
#

.

#

async def timeout(ctx, member: discord.Member=None, time : int,*, reason=None): getting error of non defauly arguement at time followes a default arguement

light violet
#

Help me pls

maiden fable
light violet
#

I dont want the member as comoulsory

maiden fable
#

Then do that
What I sent

narrow cradle
#

it still doesnt work

narrow cradle
#

used stacks overflow, works

robust fulcrum
#

Guys is it possible to host discord bot on netlify?

slate swan
#

no, Netifly is used to host webpages

#

hello how do i make a slash command bot send my embed?

slate swan
#

hello how do i make a slash command bot send my embed?

robust fulcrum
light violet
#

How to get the list of banned members in a server

slate swan
#

thanks

slate swan
light violet
#

How do i calculate number of banned members in a server

slate swan
#

yea

slate swan
slate swan
light violet
#

@slate swan no code i want that for my server info command

slate swan
#
intents = discord.Intents.default()
intents.members = True
bot = discord.Bot(intents=intents,command_prefix='!')

@discord.ext.commands.guild_only()
@bot.slash_command(name="mines", description="game")
async def mines(ctx, server_hash):
    round_id = str(server_hash)
    round_length = len(server_hash)
    if round_length < 64:
        await ctx.respond(embed=discord.Embed(description="**invalid.**",color=FF0000))
    elif round_length == 64:
        sleep(5)
#

ctx?

#

yea

#

has this worked tho?

slate swan
slate swan
#

shouldnt it be interaction: discord.Interaction

#

where?

#

replacing the ctx

#

lemme try'

#

like that?

#

is server hash an integer btw?

#

integer? i dont understand

#

oh yea

#

where you have server_hash replace it with server_hash: str

#

and then change the ctx.respond with interaction.response.send_message

#

and see if that works; please mind me i dont use discord.py

#

okay

#

lemme try

slate swan
digital charm
#

Code:

  @discord.ui.button(label="Mars", custom_id="Mars", style=discord.ButtonStyle.blurple)
  async def planet4(self, button: discord.ui.button, interaction: discord.Interaction):
    await interaction.response.send_message("You've chosen the 4th planet, Mars")
    self.value = None
    self.stop

Error:

line 99, in planet4
    await interaction.response.send_message("You've chosen the 4th planet, Mars")
AttributeError: 'Button' object has no attribute 'response'
slate swan
#

so I was using the music bot example with the help of wavelink, mentioned in the docs of Pycord, I setup a lavalink server and all, but everytime the command is executed I get this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('my lavalink server url with song name ')

google says it's because no output is being passed?
relevant links:
https://guide.pycord.dev/voice/playing

any help would be appreciated

Pycord and Wavelink try to keep the playing of audio as simple and easy as possible, to keep making Discord

slate swan
slate swan
slate swan
#

sigh

#

you should know this?

#
Traceback (most recent call last):
  File "C:\Users\i\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\i\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
    await injected(ctx)
  File "C:\Users\i\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

looks like copy paste code

#

ye

#

@slate swan go watchs yt tutorial or sumtin or read the docs

slate swan
slate swan
slate swan
#

is that daki

#

i was asking where were you writing your code

digital charm
#

would I be using custom_ids from buttons to store a specific data for sending something related to that button and it varies.... If yes is this how I would store a custom_id, for a planet selected from a button(using python 3.9x and aiosqlite):

db = await aiosqlite.connect('player_data.db')
    await asyncio.sleep(2.5)
    async with db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS planet(user_id, planets_id)")
    await db.commit()

async def planets(user):
  db = await aiosqlite.connect('player_data.db')
  async with db.cursor() as cursor:
    await cursor.execute("INSERT INTO planet VALUES(?, ?)", (user.id, custom_id,))
    await db.commit()
    return
``` and so on...
slate swan
digital charm
digital charm
slate swan
#

you can use aws or Google cloud

#

or sarth'll host it for you but will need your cc

#

💃 I can't even run myself rn, imagine running a python file

#

erro?

#

error*

gaunt ice
#

@slate swan are u working on a counting system?

#

maybe use a json file to update the counting numbers

#

like for every msg it checks whether that number is right and then it updates in json file

#

idk I'm kinda new to python

#

wait

#

u use SQL?

#

hm ur right

#

what abt the indentations

#

can u show from the starting of the event

robust fulcrum
slate swan
#

Hey!

I have a role info command i am trying to make:

Code:
embed.add_field(name="Who has the role", value=role.members, inline=False)
embed.add_field(name="Permissions", value=role.permissions)

But this is what it displays:

[<Member id=755155481458114630 name='api' discriminator='0002' bot=False nick=None guild=<Guild id=1009090888997281872 name="Carti's Studio" shard_id=0 chunked=True member_count=8>>]
Permissions
<Permissions value=1071698660937>

I want it to Ping who has the role, and say what permissions it has not the value

digital charm
slate swan
slate swan
slate swan
#

idk how permissions values are resolved so cant help much with thay

slate swan
#

in the place of
role.members

value=", ".join(...)```
#

thank you<3

slate swan
#

why i have error?

#

i need help

shrewd apex
slate swan
shrewd apex
#

what does the error say?

slate swan
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
shrewd apex
#

mix of spaces and tabs?

slate swan
shrewd apex
#

uhuh u cant use both spaces and tabs to indent

#

stick to one

slate swan
#

can u change code to correct and send me? I dont see spaces and tabs in one line

#

@shrewd apex

naive briar
#

That could happen when the discord.Intents.guilds is disabled or the message is sent in DMs

#

Before you do anything that requires guild, you have to check if message.guild returns None

#

If you want to

slate swan
#

any1 can help with discord.ext.commands error?

naive briar
#

What's the error

slate swan
#

sending ss wait

#

btw any1 can help me with requests?

#

@shrewd apex

#

that's my theme

slate swan
#

if i want to do an if for each message then how do i do it?

#
        if self.values[0] == 'say':
            await interaction.response.send_message("say")

        if self.values[1] == 'ban':
            await interaction.response.send_message("ban")

        if self.values[3] == 'kick':
            await interaction.response.send_message("kick")

etc```
naive briar
#

That would cause an error since if the message was sent in DMs, the message.guild would return None. I'd say just return it if the guild was None and if your on_message event is only for afk things

async def on_message(message):
    ...
    if not message.guild:
        return
    ...
slate swan
slate swan
naive briar
slate swan
#

i have made

robust fulcrum
#

Guys i want to make a level system in my discos bot Rpg
I already have a exp system
I want that like when user have more than 100 exp he reached level 2 and level 3 on 200 exp and level 4 on 400 exp and vice versa
Can anyone help me how to can i it?
It would be a nightmare for me to make if else statements for 100 levels

naive briar
#

I'm not sure what your on_message event has, but I think you should put that above the line that you're trying to get guild from the message

naive briar
#

That looks about right to me

slate swan
#

I'm using hikari slash commands library and people can use / commands in the bots direct messgaes, how could i disable that?

robust fulcrum
#

I have once made a afk command you can see that to take idea

bright wedge
#

member.avatar.url

#

you define member as membre right?

#

membre.avatar.url

#

try this

naive briar
#

Which part of it? I don't know how your AFK system works

robust fulcrum
#

Are you using a database?

bright wedge
#

you never define the format

#

the data_format

#

try something like that

#
member.joined_at.strftime("%d/%m/%Y %H:%M:%S"))
#

no

#

what version you are using? the new one right?

#

idk this. in new discord version we have theses changes

#

avatar_url -> avatar.url
avatar_url.read() -> avatar.read()
avatar_url_as() -> avatar.replace()

#

send the code again sir

naive briar
#

I honestly don't know what is wrong here, since I pretty much don't know how your AFK welcome back thingy works. Sorry if I can't help

bright wedge
#

wanna see my userinfo command?

#

and do your changes because im coding something else now

#
#    ----------------------------------------------------
#                    USERINFO - COMMAND
#    ----------------------------------------------------

    @commands.command(aliases=['Userinfo', 'User', 'user', 'USERINFO'])
    @commands.has_permissions(administrator = True)
    async def userinfo(self, ctx, member : discord.Member):
        accountage = (discord.utils.utcnow()) - (member.created_at)
        time = int(accountage.total_seconds())
        day = time // (24 * 3600)
        time = time % (24 * 3600)
        hour = time // 3600
        time %= 3600
        minutes = time // 60
        time %= 60
        
        roles = [role for role in member.roles[1:]]
        embed = discord.Embed(colour=member.color, timestamp=ctx.message.created_at)
        embed.set_author(name=f"{member.display_name}#{member.discriminator}", icon_url=member.avatar.url)
        embed.set_thumbnail(url=member.avatar.url)
        embed.add_field(name="**Όνομα Χρήστη:**", value=f'{member.mention}')
        embed.add_field(name="Ημερομηνία δημιουργίας λογαριασμού:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline=False)
        embed.add_field(name="Ημερομηνία Συμμετοχής: ", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
        embed.add_field(name="Διάρκεια Λογιαριασμού:", value=f"{day} Ημέρες, {hour} Ωρες, {minutes} Λεπτά", inline=False)
        embed.add_field(name=f"Ρόλοι [{len(roles)}]:", value=" ".join([role.mention for role in roles]))
        embed.add_field(name="Top role:", value=member.top_role.mention, inline=False)
        embed.set_footer(text=f"ID: {member.id}", icon_url=ctx.author.avatar.url)
        await ctx.send(embed=embed)
slate swan
#

why it isnt working

winged coral
#

Can you be more specific

slate swan
#

that's slash command i user can select channel to send his message.

winged coral
#

Few things wrong

#

You're accessing the context channel anyway, which isn't the specified "kanal"

#

Secondly, you're using the * operator to denote the "text" attribute as filling the remaining slots

#

The kanal arg cannot be set regardless of input

#

The parser greedily consumes remaining arguments indiscriminately and sets them all to text

indigo basalt
#

I am trying pycord and the code is working but only sometimes. BUT
Sometimes it shows the Commands in discord
Sometimes it shows them without description or it shows the description only the first time using it
Sometimes it shows them and after using them they disappear
And Sometimes it doesn´t show the Commands at all
Has anyone a clue what could be the issue. I used the bot token before with discord.py and that might cause some issues but that is the only thing i can think of but maybe one of you has an Idea. Thanks in Advance

winged coral
#

The token being used with d.py shouldn't be an issue but there could be leftover registered commands

#

I'm not familiar with pycord but they should have a flush function somewhere that clears the bot tree

indigo basalt
#

Ok thank you i look for sth like that

robust fulcrum
#

Guys i want to make a level system in my discos bot Rpg
I already have a exp system
I want that like when user have more than 100 exp he reached level 2 and level 3 on 200 exp and level 4 on 400 exp and vice versa
Can anyone help me how to can i it?
It would be a nightmare for me to make if else statements for 100 levels

#

Bro you need to define index first before adding value to it

bright wedge
#
msg = await ctx.send(content="**🎉 GIVEAWAY 🎉**", embed=embed1)
        await msg.add_reaction("🎉")
        await asyncio.sleep(timewait)
        message = await ctx.fetch_message(msg.id)
        for reaction in message.reactions:
            if str(reaction.emoji) == "🎉":
                users = await reaction.users().flatten()
                print(reaction.users())

 'async_generator' object has no attribute 'flatten'

rugged shadow
#

level = exp / 100

#

and update the level only if exp / 100 % 1 == 0

robust fulcrum
#

That ik but i need to make that for 100 levels and that's a headache

rugged shadow
#

no?

#

like

if exp % 100 == 0:
    level = exp / 100
robust fulcrum
#

You mean that if level is 3 user needs 300 exp? Right?

rugged shadow
#

Yes

#

Well it updates the level based on the exp

robust fulcrum
#

If user exp reached 101 what will happen?

rugged shadow
#

Nothing will happen because of the if statement

robust fulcrum
#

Won't user reach level 1?

rugged shadow
#

No

#

If the user is already level 1, but he gains 1 exp, nothing will happen

#

for every 100 exp they will gain level

robust fulcrum
#

I want that if user reaches like level 4 it should need 800 exp for level 5