#discord-bots

1 messages Β· Page 129 of 1

slate swan
#

hi guys

#

i have problem my bot is running well and all but

#

when i type the command its not working idk why

vocal snow
#

have you enabled message content intents?

#

Do you have an on_message event?

slate swan
#
async def on_message(message):
  if message.author == client.user:
    return

async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('!play'):
    await message.channel.send('now playing the song you sent')
    await message.delete()
    return```
vocal snow
#

you need to process commands

mighty yarrow
#

await asyncio.sleep(0)

slate swan
#

how

mighty yarrow
slate swan
#

ty

vocal snow
#

that makes absolutely no sense

dull terrace
mighty yarrow
#

what delay number should i put??

quick gust
#

depends

#

what u want and on what ure doing after the delay

vocal snow
#

what endpoint are you calling that you're actually getting ratelimited on?

dull terrace
#

not zero lol

slate swan
#

'builtin_function_or_method' object has no attribute 'choice'

quick gust
#

full error

dull terrace
#

if you're trying to use numpy random it's numpy.random.choice

vocal snow
#

!e ```py
from random import random

random.choice

unkempt canyonBOT
#

@vocal snow :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
main moth
#

Could send DMs but it throws an error that triggers:

await message.author.send(embed=embed)

AttributeError: 'ClientUser' object has no attribute 'send'

#

what should i change

slate swan
#

the bot can't dm itself

main moth
#

and how to fix?

#
async def on_message(message):
    if not message.guild:
        embed=discord.Embed(title="DM this Bot is not allowed!", url="url", description="whoops this isn't in a server this is in dms", color=discord.Color.blue())
        await message.author.send(embed=embed)
        return
#

@slate swan

naive briar
#

Check if the author is a bot or not probably 🀷

slate swan
#

so why on message command

#

stopped working thats annoying

wicked atlas
#

Are your message content intents enabled?

slate swan
#

yes

wicked atlas
#

Just make one function

slate swan
wicked atlas
# slate swan @ bot.event?

Yes, you use that to make a function an event handler. Just make a single on_message function, put that decorator on it, and put all your code under that

#

Don’t make two on_message functions with bot.event, one of them will end up overriding the other

slate swan
#
async def on_ready():
  print(f'Logged in as {Client.user}')

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

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

  if message.content.startswith('!play'):
    await message.channel.send('now playing the song you sent')
    await message.delete()```
wicked atlas
#

Looks like of of them is redundant anyway

primal token
#

Why does your Client instance have CamelCase?

wicked atlas
#

Yeah, why is it different from what you had initially?

slate swan
#

i adjusted it

#

becs i tried to put bot instead of client everywhere

wicked atlas
# slate swan i adjusted it

Adjust it back, only use snake_case for everything except classes. Makes it clear what is a class and what isn’t.

primal token
#

Not for everything

#

constants use SCREAMING_SNAKE_CASE

wicked atlas
#

Oh, and constants yes ah

#

Forgot about them

primal token
#

πŸ‘

slate swan
#

logging module: hold my beer 🍻

primal token
#

I still dont understand why they havent made a pr to change the namespaces

wicked atlas
primal token
#

it's a bit odd seeing camelCase in your python code lol

slate swan
#


intents = discord.Intents.all()

client = discord.Client(intents=intents)



token = ''


@client.event
async def on_ready():
  print(f'Logged in as {client.user}')

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

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

  if message.content.startswith('!play'):
    await message.channel.send('now playing the song you sent')
    await message.delete()

client.run(token)```
wicked atlas
#

Well?

#

Does it work? You’ve still got that second on_message.

primal token
slate swan
#

its online

#

should i delete await on function?

slate swan
wicked atlas
primal token
#

πŸ™ˆ

slate swan
#

delete and make new function? await message.channel.send('now playing the song you sent')

slate swan
#

im confused sry

wicked atlas
#

You have two on_message event functions. That second one will overwrite the first one, but the first one technically doesn’t do anything.

slate swan
#

mhm

#

i see.....

#

then ima change it to on_delete_message

#

i wasnt aware sry if i wasted ur time @wicked atlas

#

wait nvm

wicked atlas
wicked atlas
slate swan
#

i got it this time

wicked atlas
slate swan
#

i had the same on message function

wicked atlas
#

You could just delete that first on_message function alltogether?

slate swan
#

it worked

#

@wicked atlas thanks u taught me something thanks a bunch

wicked atlas
#

πŸ‘

winged linden
#

Anyone know why this doesn't work?

@tree.command(name = "addusertorep", description = "Adds a user to the database for Valcarries", guild = discord.Object(id = bot.guild_id))

async def addusertorep(interaction: discord.Interaction, user: discord.Member, startingrep: int):

    async with aiosqlite.connect(r"C:\Users\Fiery\OneDrive\Desktop\AtomProjects\HyperionFund\Databases\Database.db") as db:
        values = (user.Name, user.id, startingrep)
        await db.execute("""INSERT INTO RepStorage (Username, DiscordID, RepAmount) values ( ?, ?, ?)""", values)
        await db.commit()
#

I get this error ```py
discord.app_commands.errors.CommandInvokeError: Command 'addusertorep' raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.

hushed galleon
#

thats sqlite telling you the first value you passed to your query cant be understood

#

user.Name shouldnt exist though

winged linden
#

What do you mean it shouldn't exist

hushed galleon
#

the actual attribute you're probably referring to is .name, lowercase

winged linden
#

oh

#

Thank you πŸ™

winged linden
#

I want to create an embed and I'd like it to edit the description to add a players username when the addusertorep command is run

#

Is editing embeds possible?

hushed galleon
#

sure

#

you just need the Embed object that you're updating it to, and the Message (or PartialMessage) object that's going to be edited

winged linden
#

Well if I get the bot to post an embed can I just copy the message ID and use that to grab the embed

#

The bit im most confused about is how I would edit the description to add the new players username

hushed galleon
#

if your database stores all the information you need to create the embed, i wouldnt bother "editing" the actual embed that the message has

#

you can simply recreate the embed with what you know, and update the message with that

winged linden
#

So you mean like deleting the embed message then grabbing the username for each record and using that to create a new embed?

#

But how would I get like the messageID for the new embed and save it

hushed galleon
#

dont mix up "embeds" with the "message" itself

winged linden
#

Would I have to save it in a database too

hushed galleon
#

yes the channel and message ID would have to be saved

winged linden
#

well the channel doesn't change so I can just make a variable and put the channel in it

#

But the messageID does change so I would most likely have to store it in a database and then delete the previous record in the database?

hushed galleon
#

does the message normally change?

winged linden
#

Only the description of the message will change

#

Of the embed sorry

#

Im a little confused on what you mean by does the messgae change

hushed galleon
#

if you're referring to just editing the message, that by itself doesnt affect the message's ID

winged linden
#

Yeah but wasn't your idea to delete the message and create a new one rather than editing it?

hushed galleon
#

no, i didnt say that

winged linden
#

oh

hushed galleon
#

the Embed object can be recreated, and you can simply edit the message with your new embed object

winged linden
#

oh!

hushed galleon
#

thats what i mean by not mixing up "message" and "embed", because the message can be edited to display a new embed

winged linden
#

dang makes more sense now aha

#

I'm just confused on how I would grab the Username for all records from the table and put them into the description of the embed

#

because doesn't it return it as a tuple?

hushed galleon
#

each row would contain one user name (inside a tuple), so you have to fetch many rows at once to get all the names

winged linden
#

Isn't that watch fetchall is for?

hushed galleon
#

yeah

#

e.g. ```py
cursor = await conn.execute('SELECT name FROM players')
rows = await cursor.fetchall()

rows would look something like:

[('thegamecracks',), ('Fiery',), ...]```

winged linden
#
result1 = await db.execute("SELECT Username FROM RepStorage")
        result2 = result1.fetchall()
        
#

Since I used aiosqlite

#

Forgor await

#

But then if its returned as a tuple then how would I put it into my embed description?

hushed galleon
#

figure out how to turn it into a string that looks nice

#

if you need help with how to do that, you should ask in a help channel

alpine cove
#

!d str.join

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
winged linden
#

I remember turning a tuple into an integer previously however that was only with one record

winged linden
slate swan
#

Can someone please help me? I have the complete code for my Discord bot. It is in a .py file. How do I add the code to my bot?

winged linden
#

token being the bots token

#

then run the py file

slate swan
#

Cool thanks

alpine cove
unkempt canyonBOT
#
map

map(function, iterable, /, *iterables)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterables* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap "itertools.starmap").
winged linden
#

Yeah I sort of need them to have like a space between them

winged linden
alpine cove
#

!e

seq = [1, 2, 3, 4, 5]

try:
  print("-".join(seq))
except:
  print("1 doesnt work")

try:
  print("-".join(map(str, seq)))
except:
  print("2 doesnt work")
unkempt canyonBOT
#

@alpine cove :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1 doesnt work
002 | 1-2-3-4-5
alpine cove
winged linden
#

wait so technically could I use \n instead of - and it would print them on seperate lines?

winged linden
#

Dang alright thanks ill try it out now

alpine cove
main moth
#

Hi short question, i want that the bot is sending something when a new Record is in Database (Mysql). At the moment i am doing it with a loop but i think there should be a better way without looping, just with listining or sth like that?

@tasks.loop()
async def verification_code(cursor) -> None:

    cursor.execute("SELECT * FROM password_forgot")
    
    records = cursor.fetchall()

    print("Total number of rows in table: ", cursor.rowcount)

    print("\nPrinting each row")
    for row in records:
        print("Id = ", row[0], )
        print("Name = ", row[1])
        print("Code = ", row[2])
        print("Date  = ", row[3], "\n")


    await asyncio.sleep(10)

winged linden
#

wait how do I get a pre existing message into a variable so that I can use msg.edit

#

I have the message ID of the message however I can't find the function to get the actual message object

#

if that makes any sense

naive briar
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
winged linden
#

thanks

#

whats the / for?

naive briar
#

Positional-only argument

main moth
#

How can i do an on lookup to mysql if something have added

cloud dawn
#

Use sql

#

WHERE for example

winged linden
#

?

winged linden
#

i doubt it but it somehow went wrong

upbeat otter
#

also, both the methods are available for a Guild object too

winged linden
#

I have the text channel object so it would just be channel.fetch_message?

upbeat otter
#

sure

winged linden
#

Alright

#
discid = (user.id)
result3 = await db.execute("SELECT * From RepStorage Where DiscordID = ?", discid)
#

what will this return if no record has a discord ID matching it?

#

nil?

main moth
#

Can I send a Direct message with a Python Bot if i have only the Name with Tagg of a Person (Probably not on the same Server as the bot)

upbeat otter
slate swan
#

Im so happy

#

got that too

#

yayy

#

!ctx

#

someone help

upbeat otter
slate swan
upbeat otter
feral frost
upbeat otter
unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
slate swan
slate swan
#

Tyyy

slate swan
feral frost
slate swan
upbeat otter
slate swan
naive briar
#

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

feral frost
slate swan
#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
feral frost
#

and how do i put it in an embed ?

slate swan
feral frost
#

but how

upbeat otter
feral frost
#

i cant use enter things

slate swan
feral frost
#

no

feral frost
#

like look

slate swan
#

i think you can't do it in the title

upbeat otter
#

I hate my life

winged linden
naive briar
feral frost
upbeat otter
feral frost
#

ah ok

slate swan
feral frost
#

still error

upbeat otter
upbeat otter
upbeat otter
feral frost
winged linden
slate swan
#

got a problem my bot doesent want to work even if the code is the same what should i do?

upbeat otter
feral frost
#

ow huh ?

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.

slate swan
slate swan
feral frost
#

ok

#

can you just show me the code of how you do it cuz i am failing this thing

naive briar
#

!e

print("""Hello
World""")
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello
002 | World
feral frost
#

is it that

#

aah 3

#

ye now i see

#

thanks guys

slate swan
#

what is better to use?

class MyClient(discord.Client):
    async def on_message(self,message):
        if message.author.id == self.user.id:
            return
        if message.content.startswith("-hi"):
            await message.reply("hello")

or

intents = discord.Intents.default()
intents.message_content = True
bot = discord.ext.commands.Bot("-", intents=intents)

@bot.command(name="name")
async def name(ctx):
    await ctx.reply("h")
upbeat otter
winged linden
#

Error:

discord.app_commands.errors.CommandInvokeError: Command 'addusertorep' raised an exception: ValueError: parameters are of unsupported type

Code:

async with aiosqlite.connect(r"C:\Users\Fiery\OneDrive\Desktop\AtomProjects\HyperionFund\Databases\Database.db") as db:
        values = (user.name, user.id, startingrep)
        discid = (user.id)
        result3 = await db.execute("SELECT * From RepStorage Where DiscordID = ?", int(discid))
        result4 = result3.fetchone()
        if result4 == None:
upbeat otter
#

oh hi Asher

shrewd apex
#

bruh wdym outdated commands.Bot is subclass of Client

upbeat otter
winged linden
#

ok

upbeat otter
naive briar
shrewd apex
#

then how is it 'outdated'?

winged linden
upbeat otter
upbeat otter
slate swan
#

so should i use Bot or Client

shrewd apex
#

client is for interactions only bot ie app commands

slate swan
upbeat otter
shrewd apex
#

commands.bot allows prefix commands and allows cogs

slate swan
shrewd apex
feral frost
#

how can i split buttons up into custom_id ? like how can i do the "if custom_id == blablabla" ?

upbeat otter
upbeat otter
#

Client isn't only for slash commands lmao (I know you know so)

slate swan
#

oh

shrewd apex
slate swan
#
@client.event
async def on_message(message):
  if message.author != client.user:
    msg = message.content
    await client.process_commands(msg.content.lower())
Traceback (most recent call last):
  File "/home/runner/game-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 19, in on_message
    await client.process_commands(msg.content.lower())
AttributeError: 'str' object has no attribute 'content'
upbeat otter
winged linden
winged linden
#

i defined it as integer in database

slate swan
slate swan
winged linden
#

and I made sure that user.id was an integer by doing (int)

upbeat otter
winged linden
winged linden
#

It should be an integer already anyway

#

Ill try it

upbeat otter
slate swan
winged linden
#

hence why im trying it

upbeat otter
shrewd apex
slate swan
#
@client.event
async def on_message(message):
  # if message.author != client.user:
    # you dont really need this part
  msg = message.content
  blah blah blah

(im not very experienced so my apologies if it doesnt work)

winged linden
# shrewd apex send ur function
async def addusertorep(interaction: discord.Interaction, user: discord.Member, startingrep: int):

    async with aiosqlite.connect(r"C:\Users\iamro\OneDrive\Desktop\AtomProjects\HyperionFund\Databases\Database.db") as db:
        values = (user.name, user.id, startingrep)
        discid = (user.id)
        result3 = await db.execute("SELECT * From RepStorage Where DiscordID = ?", int(discid,))
        result4 = result3.fetchone()
        if result4 == None:
slate swan
#

@slate swan

winged linden
#

its a slash command btw

slate swan
#

got it with this so now commands arent case sensitive πŸ‘

#

smart

#

i might steal that

upbeat otter
winged linden
#

alr

shrewd apex
upbeat otter
#

oh yeah

shrewd apex
#

and if it dosent exist its gonna return an empty iterable

#

from latest dpy version yes

slate swan
#


{"1031053618008301588": {"money": 4092, "bank": 3432423, "totalmny": 28993}, "994474388042813450": {"money": 1536, "bank": 5000, "totalmny": 1536}, "950652516708782120": {"money": 1331, "bank": 5000, "totalmny": 1664}, "812729257968009256": {"money": 1500, "bank": 5000, "totalmny": 1500}, "1022261701850169445": {"money": 1500, "bank": 5000, "totalmny": 1500}, "695051432302346271": {"money": 1500, "bank": 5000, "totalmny": 1500}}
shrewd apex
#

yes

winged linden
shrewd apex
#

lemme check the docs i dont use aiosqlite

#
async fetchone() β†’ Optional[sqlite3.Row]
Fetch a single row.
#

yeah None

#

i dont think so coz if u pass datetime the task loop is supposed to run at that point in time everyday not sure if u can put multiple kwargs never tested

winged linden
winged linden
#

ye i did

#

did not

shrewd apex
#

not really

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
shrewd apex
#

it can take integers too

#

i store a timestamp in db and use that in the taskloop to find timedelta and calculate

#

if the bot restarts the loop starts again

slate swan
#

i love making economy bots (totally)

shrewd apex
#
@tasks.loop(hours=12)
async def my_loop() -> None:
  old_time = datetime.fromtimestamp(await bot.db.get_time())
  if (datetime.datetime.utcnow() - old_time).days >= 7:
    ...
#

something along these lines

sick birch
#

yes

winged linden
#
discord.app_commands.errors.CommandInvokeError: Command 'addusertorep' raised an exception: ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.
shrewd apex
#

dosent seem related to the query

winged linden
#
result3 = await db.execute("SELECT * From RepStorage Where DiscordID = ?", ("", discid))
shrewd apex
#

bro

#

it was an example

#

"" <-- means the sql query

#

πŸ—Ώ

winged linden
#

😭

#

I had it like this before though

result3 = await db.execute("SELECT * From RepStorage Where DiscordID = ?", (discid))
#

and it wasnt working

rustic edge
#

How do I timeout a user?

shrewd apex
#

result3 = await db.execute("SELECT * From RepStorage Where DiscordID = ?", (discid,))

waxen cradle
#

how can i modify this line so that the bot can send the message to the 1st text channel of every guild?

naive briar
unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
rustic edge
#

ty

vocal snow
rustic edge
sick birch
waxen cradle
#

thx guys

slate swan
#

discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.

naive briar
#

Enable message_content intent

winged linden
#

Anyone know how i get it to not have these brackets and parenthesis?

slate swan
slate swan
# slate swan

discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.

naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

β€’ The message was sent by the client

β€’ The message was sent in direct messages

β€’ The message mentions the client

This applies to the following events...

winged linden
#
await db.execute("""INSERT INTO RepStorage (Username, DiscordID, RepAmount) values ( ?, ?, ?)""", values)
            await db.commit()
            await interaction.response.send_message(f"Succesfully added the user {user.name} to the database!")
            result1 = await db.execute("SELECT Username FROM RepStorage")
            result2 = await result1.fetchall()
            channel = interaction.guild.get_channel(bot.valcarrierchannel)
            message1 = await channel.fetch_message(bot.valcarriermessage)


            embed = discord.Embed(title = "List Of Verified ValCarriers", description = ("\n".join(map(str, result2))) )
            embed.set_thumbnail(url = "exampleURL")
            await message1.edit(embed = embed)
#

my code ^^

naive briar
winged linden
naive briar
#

It's just converting elements in result2 to string and join them

winged linden
#

so how would I get the string from the tuple and then join them

naive briar
#

I would use for loop

winged linden
#

wah

#

How would a for loop even come into the equation

naive briar
#

!e

result2 = (("mmm",), ("000",))
print("\n".join(i[0] for i in result2))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | mmm
002 | 000
naive briar
#

🀷

winged linden
#

oh damn

#

lol

shrewd apex
#

!e

result2 = (("mmm",), ("000",))
print (sum(result2, tuple()))
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.

('mmm', '000')
shrewd apex
#

python pBlush

naive briar
#

😳

weary flume
#

is there a way to use mongodb to take away a role tmrw

shrewd apex
#

mongodb to take away a discird role?

weary flume
#

ye

shrewd apex
#

oh i thought i read it wrong phew

#

no u cant

slate swan
#

how can i make a command that reads a number after the command like im using this but i want to specify that amount on discord ```@bot.command()
async def ren(ctx, amount=100):
await ctx.channel.purge(limit=amount)

shrewd apex
#

instead u can use discord to take away a discord role

shrewd apex
#

or whatevere number u want

slate swan
#

it needs to read the number after but idk how

#

since there its just deleting in the limit

shrewd apex
#

how do u enter the command?

slate swan
#

like 100 thats how much messages it will delete

slate swan
#

i use ΓΈ since its easier for me

slate swan
shrewd apex
#

what happend when u type ΓΈren <ur_number_here>

slate swan
shrewd apex
#

bro just enter a number other than 100

slate swan
#

since it deletes in the limit=amount

shrewd apex
#

thats the whole point of commands

slate swan
#

but i want to type it on discord not on the script

shrewd apex
#

πŸ—Ώ

#

ΓΈren <type_ur_number_here>

#

am i still not obvious enough?

winged linden
#

I need to create a leaderboard command for my database,
I need to somehow match all records that have the same UUID
then I need to add the Column Called Amount for all the records with the same UUID
and then I need to compare the sum against other UUIDS to find the top 10 with the most total Amount.

Where do I even begin?

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

sorry 🫑

slate swan
winged linden
shrewd apex
#

similar syntax

winged linden
shrewd apex
#

basically pseudocode select * from table where x = ? order by whatever acs/dsc limit 10

winged linden
#

but like

#

its hard to explain what I mean

shrewd apex
#

also if u need sum of selected values use the sum() in sql

winged linden
#

Multiple records will have the same UUID

cloud dawn
#

We sadly aren't wizards we need to know how your DB is structured.

winged linden
#

Yeah Ik

#

Im trying to explain it but its hard to put into the right words

shrewd apex
#

why is it like this tho?

winged linden
#

Like so when a new donation is logged it creates a record with their UUID, username and the Amount

shrewd apex
#

whats wrong with just updating a single value

cloud dawn
#

Why even have the username

shrewd apex
#

my guess is uuid is not generated by him

winged linden
#

The UUID is retrieved from the username

#

via mojang api

shrewd apex
#

bro just use the user id

winged linden
#

It needs to be the UUID

#

its for minecraft

shrewd apex
#

dosent explain why u need two rows

winged linden
#

The username can change

#

Wait no

#

The two rows are seperate donations

#

just from the same person

shrewd apex
#

this api doesnt support lists? also why u need them seperate?

winged linden
#

To get the UUID

#

I need the username

cloud dawn
#

I will make a query I'm mid game rn tough lol

winged linden
#

and vice versa

shrewd apex
#

"SELECT UUID FROM table WHERE Username = ? ORDER BY SUM(AMOUNT) DESC LIMIT 10"

#

on these lines mind u i aint done sql in like 2 months so not sure

winged linden
#

But heres my issue

cloud dawn
winged linden
#

Like The sum of all amounts would have to be the sum of the amounts with a certain UUID

shrewd apex
winged linden
#

and I have to check this for every UUID in the table

shrewd apex
#

or similar rows

winged linden
#

And then find the top 10 totals

shrewd apex
#

bro y are u making multiple rows in first place then

winged linden
#

I thought that would be the best option at the time

#

But now its made it more complicated

#

I guess I could change the code to add to amount if the user is already in the database

cloud dawn
#

Yeah for this query we need to debug since this is not a small query lol

#

Lemme fire up a dummy db

winged linden
#

I just started changing my code so that each UUID would only have one record

split rover
#

In a Slash command how do i add an argument as a user

winged linden
#

an argument as a user?

#

wdym

split rover
#

Sorry, I mean like when you use a slash command it asks you for a user

winged linden
#

like /test @winged linden ?

split rover
#

yeah

winged linden
#
user: discord.Member
split rover
#

but in slash command form

winged linden
#

I believe

split rover
winged linden
#
async def test(interaction: discord.Interaction, user: discord.Member)
shrewd apex
#

i can do it in 2 queries not sure about one

#

actually one also possible

#

just fetch all data then sum up and sort the list get first ten

winged linden
slate swan
#

anyone want to work on my economy bot with me I have like 8 cmds

teal glade
#

I want to add a UI button to a cog, but I get this error:

TypeError: expected an instance of View not <class 'type'>
winged linden
mild nimbus
#

what do i do here?

shrewd apex
#

ok figured it out

naive briar
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.

slate swan
winged linden
#

this is mainly for help

slate swan
#

oh

shrewd apex
#

"SELECT Username, SUM(Amount) FROM mytable GROUP BY UUID ORDER BY SUM(Amount) DESC LIMIT 10"

cloud dawn
shrewd apex
#

gurantee it works

split rover
winged linden
#

I have been trying to tell you i WAS changing my code

waxen cradle
#

what did i miss here? i want to loop through every channel and send a message, the bot starts with no errors but it doesnt send anything

shrewd apex
#

ik i took it as an assignment or something

split rover
shrewd apex
#

wanted to find the answer

#

its upto u to use or not

cloud dawn
sick birch
cloud dawn
waxen cradle
cloud dawn
slate swan
#

i dont want to mess with slash commands they seem hard πŸ₯Ί

sick birch
winged linden
mild nimbus
naive briar
#

There's literally an example on the embed

winged linden
#

😭

shrewd apex
teal glade
winged linden
#

And we were going to log all the donations we handed out

slate swan
#

W

winged linden
#

but its a little time consuming to run a command considering theres 100s of people daily

winged linden
shrewd apex
#

how do they donate?

winged linden
#

On minecraft via trading

#

I'd have to make a minecraft mod

#

but i do not know java 😦

slate swan
#

never thouht of getting the channel

shrewd apex
#

oh rip nvm idk mc either but if can create a webhook and trigger it everytime someone donates that might do the job

winged linden
#

Yeah it would but I also have to change the database when donation

#

And even like detecting when someone donates will be difficult

#

since its not like theres any api which tells you when someone trades

#

hypixel aint making it easy

#

so for now we are just changing it to where we log the total amount we give out per day

#

and then when I understand how to make a mc mod I can revert back to this system

slate swan
#

hypixel is an L (Ive never played it)

teal glade
sick birch
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.

cloud dawn
slate swan
#

so i found some code about breach checking and i want to make the print commands into message.channel.send so it doesnt print the output but it sends it to the user

[2022-11-11 19:23:45] [INFO    ] discord.client: logging in using static token
[2022-11-11 19:23:47] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 0e7114365fa541c3d2d29c0176a77625).
C:\Users\marko\Desktop\Heroku-Bot-main\main.py:106: RuntimeWarning: coroutine 'init_example' was never awaited
  init_example()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

https://paste.pythondiscord.com/yudoledini

sick birch
#

Not being combative I'm just curious

cloud dawn
#

Since dank memer is not in the app discovery because of the economy

slate swan
sick birch
cloud dawn
limber pagoda
#

wait so

sick birch
limber pagoda
#

am i required to remove my gambling commands from my bot

cloud dawn
slate swan
sick birch
#

It's just so many people do economy bots so I want to make sure that it's TOS violating

#

Also this is news to me :p

sick birch
limber pagoda
sick birch
#

I would suggest you remove that like because you're going to be adding the view soon anyway

#

You'd be adding it twice

teal glade
#

ohhhh

#

hmm im blind

limber pagoda
teal glade
#

If it's for real-world value, yes

limber pagoda
#

its just my bot currency

#

not irl currency

limber pagoda
teal glade
#

If there is no real money in line, then I guess you're safe

cloud dawn
#

@sick birch It's complicated.

#
cloud dawn
primal token
#

Most economy bots dont offer real world value but value in their own coins

teal glade
cloud dawn
primal token
#

Either way most economy bots dont offer gambling, even if something is addicting i doubt they would care enough, after all addiction is a very sensitive topic

#

Allot of gatekeeping would appose from such discussion

slate swan
#

can anyone help me make a message transcript for tickets?

#
fileName = f"{ctx.channel.name}.txt"
with open(fileName, "w") as file:
    async for msg in ctx.channel.history(limit=None):
        file.write(f"{msg.created_at} - 
                   {msg.author.display_name}: 
                   {msg.clean_content}\n")
#

I have this but i need help implementing it

slate swan
#

how do I get the time a message was created at?

#

is any1 able to help me make sum its a few lines of code and would help me so much :)) dm

naive briar
#

Are you sure that the API is actually returning an image?

slate swan
#

like how do you make the bot copy your message and return it in a message?

#

u didnt process cmds

#

await client.process_commands(message)
or
await bot.process_commands(message)

dense flower
naive briar
#

The same one as the embed's image?

dense flower
#

oh ill try that

slate swan
#

like how do you make the bot copy your message and return it in a message??

#

@slate swan

#

yo

naive briar
#

Do you have message_content intent enabled

slate swan
#

do this

@client.event
async def on_message(message):
  msg = message.content 
  await message.channel.send(msg)
#

@slate swan

#

forgot to add something

#

which

#
@client.event
async def on_message(message):
  msg = message.content 
  if message.author != client.user:
    await message.channel.send(msg)
dense flower
slate swan
#

@dense flower

#

for?

#

that was for the other guy

slate swan
#

idk

dense flower
naive briar
slate swan
#

anywhere in your on_message

#

put it at the very top

#

if u rlly care

#

tickets yay

winged linden
#

how do you make an argument optional in a slash command?

dense flower
# slate swan ohh

AttributeError: 'aclient' object has no attribute 'process_commands' 😒

slate swan
#

@dense flower send me the code

naive briar
#

discord.Client doesn't have process_commands method

#

Only discord.ext.commands.Bot

#

And he's making his commands in on_message event for some odd reason

slate swan
#

yea idk why

waxen igloo
#

i use this & it doesnt work

#

if i mistype a sub command it still sends the parent

glad cradle
silent portal
#

How can I make the discord.Buttons all next to each other instead of like under each other?

slate swan
#

how do you make code stop and wait for user to write

glad cradle
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
silent portal
#

thanks

glad cradle
#

a row can contains up to 5 buttons

#

and a message can have up to 5 action rows

silent portal
fading marlin
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
glad cradle
#

0 <= row <= 4

silent portal
#

ty

dense flower
#

I know this is an incredibly lazy way to make an embed but does anyone know why when I type !insertembed i'm not getting the embed back?```py
@client.event
async def on_message(message):
if message.content.startswith('!insertembed'):
embedVar = discord.Embed(title="Title", description="", color=0x00ff00)
embedVar.add_field(name="line1", value="",inline=False)
embedVar.add_field(name="line2", value="",inline=False)
embedVar.add_field(name="line3", value="",inline=False)
await message.channel.send(embed=embedVar)

    msg = 'Hi {0.author.mention}'.format(message)
    await client.send_message(message.channel, msg)```
fading marlin
#

send_message has been gone for an aeon

#

probably consider using a bot instead of a client too

dense flower
# fading marlin probably consider using a bot instead of a client too

oh so trash this? ```py
class aclient(discord.Client):
def init(self):
super().init(intents=discord.Intents.default())
self.synced = False

async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild=discord.Object(id=1040618103249326181))
self.synced = True
print(f"We have logged in as {self.user}.")```?

fading marlin
#

if you're gonna be coding commands, I'd recommend it, yes. Also, don't sync automatically either

dense flower
ivory vortex
#

is there any way to accept an attachment through slash commands

fading marlin
#

use discord.Attachment as the arg type hint

ivory vortex
fading marlin
#

!d discord.Attachment

unkempt canyonBOT
#

class discord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
fading marlin
#

use the url attribute

orchid smelt
#

anyone familiar with this error msg

#

WARNING discord.gateway Shard ID None heartbeat blocked for more than 10 seconds.

fading marlin
#

you're blocking

orchid smelt
#

my bot is still working fine but it spit out this error msg every once in a while

#

blocking?

orchid smelt
#

ty ty

visual yarrow
#

@slate swan Don't advertise paid work here please.

obtuse blaze
#

How can I disable all commands on dms of bot?

teal glade
#

Hosting service?

fading marlin
fading marlin
unkempt canyonBOT
#

@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

This check raises a special exception, [`PrivateMessageOnly`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.PrivateMessageOnly "discord.ext.commands.PrivateMessageOnly") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

New in version 1.1.
wicked atlas
#

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

dense flower
slate swan
#
    data = r.json()['objects']

    for all in data:
        indice = all['level']

        embed.add_field(
            name = 'level',
            value = f'{indice}'
        )``` how to display all the values that are printed in the value field
#

enable it from the dev portal

#

read the full error for god's sake

#

you gotta run the code again though, did you?

#

and whats the full error you get

dense flower
#

everyone makes mistakes when starting out, allow it

#

^

slate swan
#

can you send the full error in pastebin, cant really guess with the partial one

#

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

dense flower
#

you haven't set your token x

#

oh i mean if ur using replit u should set ur token as a secret anyway

slate swan
#

just use default intents as long as you don't actually need them

dense flower
#

discord.Intents.default() for start

#

change your intents

#

to discord at the start

#

bro cmon

shadow vigil
dense flower
#

bro ur the reason people shit on new people asking questions

#

ur not trying

#

i did

#

i literally said replace your intents with the line

potent quartz
#

did discord/python changed the way u interact with bots? cause all the bots I've made in the past dont work anymore

#

just put ur token in there lol

potent quartz
#

ah I see

wicked atlas
potent quartz
#

thanks

#

bro just search it up on the internet

wicked atlas
#

you need to actually put in your bot token, not just the text token

potent quartz
#

smh

wicked atlas
#

In what way does it not work?

potent quartz
#

show the errror you get when u run it with the code

wicked atlas
#

you need to pass the intents object you've created to your client

client = discord.Client(intents = intents)
#

you sure?

#

shouldn't be

slate swan
#

There isn't some built-in user-level cooldown system for Discord buttons in discord.py is there?

wicked atlas
#

Can you show the error?

mighty pilot
#

Show your code with the intents

#

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

mighty pilot
#

You need to define it then

#

Well idk what any of that means but do you have intents enabled on the developer portal

#

Then you need to enable them all in your code as well. You only enabled default and members

slate swan
mighty pilot
#

The same way you did members but with the rest

#

Or turn off the ones you don't need in the dev portal if you only need members

wicked atlas
#

that one looks like a replit issue πŸ’€

#

one of the reasons you don't host bots on replit

mighty pilot
#

Or change default to all

#

There's better free resources

slate swan
#

Fact: I am approaching the 500th line of code for a single slash command and it is becoming exponentially more painful to go on.

wicked atlas
#

yeah, the problem with replit is that there are many other people just like you trying to host a bot, and all these requests to the discord api are being made from one IP address. Cloudflare, the service protecting discord's apis from DDoS attacks doesn't like this large ammount of requests, and blocks the IP from making api requests. That error you're seeing has HTML for cloudflare's block page.

mighty pilot
slate swan
wicked atlas
#

maybe

keen sleet
#
async def main():

    try:
        pool_ = asyncpg.create_pool(host="*", database="*", user="*", password="*")
    except:
        pool_ = asyncpg.create_pool(host="*", database="*", user="*", password="*")
        
    async with ClientSession() as session_client, pool_ as pool:

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

        async with Bot(commands.when_mentioned, 
                             db_pool=pool, 
                             web_client=session_client, 
                             initial_extensions=['cogs.configuration', 'cogs.developer', 'cogs.info'],
                             intents=intents
                             ) as bot:
            print('starting...')
            await bot.start('...')
asyncio.run(main())

is what im using right now
bot remains offline, even after going past the print line

#

im very lost

mighty pilot
#

Depends on what you're doing

#

Depends... on what you're doing...

slate swan
#

Mods...?

mighty pilot
#

Hello(ctx)

#

I haven't ridden a bicycle in 4 years

slate swan
#

Cereal I dunno about you but I'm personally not gonna help someone to make a bot say that to someone.

mighty pilot
#

I don't think it's against rules unless we discuss it. Shall we consult <@&831776746206265384> ?

potent quartz
#

bro you still didn't get it to work @slate swan ?

mighty pilot
slate swan
#

bro did windows so bad🀺 imagine a taskbar at da top

#

totally like it as a xfce default user

mighty pilot
#

Lmao I hadn't even noticed. I did that once on accident though when I was a kid. Had to google how to change it back lol

slate swan
mighty pilot
dense flower
#

Does anyone know why @app_commannds.checks.has_any_role(adminrole) isn't affecting whether or not a user can call joined? in this block of code?py @bot.command() @app_commands.checks.has_any_role(adminrole) async def joined(ctx, member: discord.Member): """Says when a member joined.""" await ctx.send(f'{member.name} joined {discord.utils.format_dt(member.joined_at)}')

mighty pilot
#

If I'm not mistaken you need the role ID?

slate swan
slate swan
dense flower
slate swan
dense flower
slate swan
dense flower
#

Why does it differentiate between two different commands for slash and prefix πŸ’€

slate swan
#

cause prefix commands work with a message context
app commands on other hand works with interactions

mighty pilot
#

Yea I missed that you weren't using a slash command with that. They differentiate between the two with .checks.

dense flower
#

eh either way I think i've just got a decent bit to revise haha

slate swan
#

they basically wrap the Message object to a Context object

dense flower
# slate swan yes

oh yeah so like how i'm doing ?joined, but I don't understand why the same @strange knoll_commands can't be applied, is it just cause of the way it's wrote in the library?

#

probably a really dumb question lmao

#

just hoping to try wrap my head around it

slate swan
#

same goes for app commands
comamnds.has_any_role won't work on an app command

dense flower
#

so just to be clear ext.commands is for prefix, and app_commands is for /

#

ok cool

#

πŸ—’οΈ

slate swan
#

exactly, app_commands supports context menus as well

dense flower
mighty pilot
#

Yea if it says app commands it's referencing some sort of interaction based event

slate swan
#

and then there's hybrid commands which mix the slash and prefix commands

dense flower
#

to get this to work with a prefix, would I change @tree.error to @bot.event?py @tree.error async def on_app_command_error(interaction: discord.Interaction,error: discord.app_commands.AppCommandError): if isinstance(error, discord.app_commands.errors.MissingRole): await interaction.response.send_message("You don't have permission to use this command", ephemeral=True) else: await interaction.response.send_message("An error occurred, please try again later.", ephemeral=True) raise error

dense flower
dense flower
slate swan
#

yeah that shouldn't be it

dense flower
#

I think my main issue is i'm not sure where i'm looking in the docs of discord.py πŸ˜…

mighty pilot
#

You have interactions and text commands in your bot?

dense flower
#

basically just trying to set it to admin only

slate swan
unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
dense flower
#

so it wouldn't be app_commands?

slate swan
mighty pilot
dense flower
mighty pilot
#

Good luck OakL

#

Lol

slate swan
#

i wanna make a leveling bot but I'm too lazy and broke to get a proper database

dense flower
slate swan
#

mongodb bad, its okay for small scale but I'll have to pay when its used at larger scale
besides that its bson based
im looking for a sql based db

#

pgsql preferably

mighty pilot
dense flower
slate swan
slate swan
dense flower
mighty pilot
dense flower
#

I was working with some huge ass dictionaries for my dissertation but luckily some dude on reddit sent me some godly tool to help with it all

mighty pilot
slate swan
#

and discord under-documents shit

#

so its even more harder to use

slate swan
# alpine cove what tool?

i personally prefer dataclasses, attrs or typedicts if i already know what the data inside that dictionary would be

#

!pip attrs this lib is fire

unkempt canyonBOT
alpine cove
#

whats attrs tho?

slate swan
#

dataclasses but better

alpine cove
#

was just about to say

#

looks like a dataclass

little peak
#

Can someone help me? I want to add a slash command to my Bot which outputs the newest youtube video link to the output of the bot

mighty pilot
slate swan
#

it's quicker with updates and helps with backward compatibility in my case
like i can use the python 3.10 dataclasses system in 3.8 if i use attrs

little peak
mighty pilot
# little peak no :/

You should start with writing a slash command that you want to use for the link

little peak
alpine cove
mighty pilot
#

I don't think anyone will write the whole command for you but if you run into problems we can help with that

little peak
#

yk

mighty pilot
#

Doing research to see if I know how to help lol

#

I haven't done that before

little peak
#

oh okay thanks

mighty pilot
#

This one could work

little peak
#

thanks i will try it

mighty pilot
ionic garden
#

how do i only disable a button for some users?

alpine cove
alpine cove
#

nvm then

mighty pilot
alpine cove
mighty pilot
alpine cove
alpine cove
#

if id not in list:
inter.response.send_message
return

alpine cove
ionic garden
#

i'm implementing ERS in a discord bot

#

so like a card game with each player having a turn & whatnot
so i don't want a player to go if it isn't their turn

mighty pilot
#

Yea I'd just send an ephemeral message if they hit the button out of turn

ionic garden
#

k cool

alpine cove
#

self.turn being the user

ionic garden
#

kk, cool

upbeat gust
#

define 'doesnt work'

#

Traceback?

alpine cove
#

just send the traceback bruhh

mighty pilot
#

Is it because chance() isn't a list?

torn sail
#

ctx.reply is not like the print function

#

It only takes 1 argument

#

Try using f strings to join the string

#

Or adding the strings

upbeat gust
#

Again, define doesn't work

#

We can't read your mind

mighty pilot
#

f"You're: {random.choice(chance)}"

#

Should at least give you a different error

upbeat gust
#

What did you try-

torn sail
#

Missed a )

open yoke
#

I'm tryna install discord library but it keeps giving me this error

upbeat gust
#

?tag msvc

novel apexBOT
#

This is not a Modmail thread.

upbeat gust
#

Oops

rugged shadow
#

wrong server πŸ˜”

upbeat gust
#

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
Some C extension packages take time to have their wheels built when new Python versions release.

One option is to download and install wheels from https://www.lfd.uci.edu/~gohlke/pythonlibs/ if they're available.

The other option is to build them yourself.
Start by downloading and installing the Microsoft Visual C++ Build Tools from the URL in the error message.
After installing, it should open the build tools installation menu. Switch to the Individual components tab at the top.
Roughly half way down the list, find and select the latest version of MSVC build tools for your CPU architecture, most likely x64/x86.
At the end of the list, find and select the latest Windows SDK for your Windows version.
Click Install at the bottom and you should then be able to build your packages. You may need to restart your terminal/editor.

#

@open yoke

dense flower
# alpine cove what tool?

I wish I remembered, i'll see if I can find it on reddit but it basically just converted stuff you shoved in there into code/dictionaries in like 20s

open yoke
#

from that link

upbeat gust
#

I've given two options

open yoke
#

are you saying I need to update my vscode

#

or what is it your wanting me to download

upbeat gust
open yoke
#

skimmed

upbeat gust
#

Read it properly then

#

It tells you everything you need to know

iron gate
#

Just install python 3.10 instead of 3.11

open yoke
open yoke
iron gate
#

No idea. I just got here. But I had the problem earlier

hushed galleon
#

whenever the maintainers of multidict and yarl release prebuilt wheels for 3.11 then it'll be an easy install

#

but otherwise you need build tools in order for pip to compile those wheels

open yoke
hushed galleon
open yoke
little peak
#

Could someone help me? How can i get the newest youtube video link of a channel?

upbeat gust
slate swan
upbeat gust
#

!d discord.TextChannel.history

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.11)") 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...
upbeat gust
little peak
slate swan
#

im confident they mean a channel as in a youtube channel there

little peak
#

yeah

#

i already looked into yt api but i dont realy know what to do

upbeat gust
little peak
upbeat gust
#

Just because you're doing something in a discord bot doesn't make it related to discord but whatever

slate swan
#

what

#

why does it say its not a module anymore

#

poetry add pymongo in the shell

#

thanks

pliant gulch
#

Requests & Pymongo πŸ‘οΈπŸ‘οΈ

slate swan
mighty pilot
mighty pilot
slate swan
mighty pilot
#

Aws has a free one too I believe

#

Haven't used it though

slate swan
#

thats only for one year, oracle provides lifetime free VM

little peak
#

thanks i think i got it now

mighty pilot
pliant gulch
#

Oracle πŸ˜”

slate swan
#

more like java company

pliant gulch
#

Lawsuit after lawsuit, after lawsuit

#

Most recent one was about selling data about people

slate swan
#

:flattered: atleast someone will know me

round knoll
slate swan
slate swan
#

it doesnt bypass it, but you won't get ratelimited until you do something craZy

slate swan
#

yes it is

slate swan
slate swan
#

you can actually get some better ones if you check this channel's pins

#

^^

#

ok thanks

slate swan
#

python/django yes
or docker if you dockerized your bot

winged linden
#

How can I get the TOP 10 Records with the highest RepAmount from my sqlite database

slate swan
open yoke
slate swan
#

gg

slate swan
#

hi, I have a list of 100 items. I want my embed description to be from 1-10 while paginating every 1-10 out of that 100 items. How exactly would I get every 1-10 until 100?

            resp = ["1", "2", "3", "etc"]
            for count, i in enumerate(resp, start=1):
                embed = discord.Embed()
                embed.description = f"**{count}.** {i}"
slate swan
abstract kindle
#

should all my functions be async?

slate swan
abstract kindle
#

got it

#

also nice new pfp and booster icon

slate swan
#

tyty

#

whats the best free vps to host my discord bot

slate swan
#

localhost 😎

hushed galleon
#

never thought about this, but has anyone used discord.py without a gateway connection? i just thought about only calling Client.login() but not connect()

#

maybe its possible to do dpy app commands via http...

slate swan
hushed galleon
#

its still the same payload though right? id figure you could create an Interaction from that and pass it to CommandTree._from_interaction() to trigger the app command

#

and if that works, maybe views will work too

#

http bot from the comfort of dpy

torn sail
#

i made a lib

#

ive tried it an it works

slate swan
torn sail
#

discord.Client._connection.parse_interaction_create

hushed galleon
#

oh yeah that method's more convenient

torn sail
#

i remember asking u about it a while ago

hushed galleon
#

really?

torn sail
#

yep

hushed galleon
upbeat gust
# hushed galleon never thought about this, but has anyone used discord.py without a gateway conne...

The following are "raw" methods.
These are all for internal use, and could be subject to change without notification.
Only the methods for message are documented, as everything else can be done with proper class methods and possible application of discord.Object
Use only if you have to, not suitable for general consumption.

client.http.do_thing

client.http.add_reaction(channel_id, message_id, emoji)
client.http.remove_reaction(channel_id, message_id, emoji, member_id)
client.http.remove_own_reaction(channel_id, message_id, emoji)
client.http.get_reaction_users(channel_id, message_id, emoji, limit, after=None):
client.http.clear_reactions(channel_id, message_id)
client.http.pin_message(channel_id, message_id)
client.http.unpin_message(channel_id, message_id)
client.http.edit_message(channel_id, message_id, **fields) #fields can include content, etc. Embeds must be to_dict'd
client.http.delete_message(channel_id, message_id, *, reason=None)

All emojis must be a unicode string or in name:emoji format.

Alternatively, for an easier method, see ?tag partialmessage

#

There's this ig

hushed galleon
#

yeah seen that tag

upbeat gust
#

You can look through the source for other http methods