#discord-bots

1 messages · Page 91 of 1

tidal hawk
#

If I host for 4 clients, then it's already 50$ profit

brazen raft
#

I get it you make personal server bots then

tidal hawk
#

Doesn't work?

wet oasis
#

How to download a module in python

tidal hawk
#

pip install module

cold sonnet
#

man's faster than google

#

still why not use google

tidal hawk
#

Wdym it's not printing that the bot is on

distant pendant
#

How can I programm a music bot

tidal hawk
#

Youtube music?

distant pendant
#

youtube or spotify

tidal hawk
#

Youtube music bot is against tos

#

Send the line where it should print that

patent wagon
#

I found some hardware to store the bot

#

I mean to host it

#

How much ram does it take on average

#

Also what are some usefull tips if I'm trying to sell the bot

#

Security wise

slate swan
#

so when i try to type a cmd

#

it dosent show

#

and the bot is up

#

please help

brazen raft
slate swan
#

pls help me my bot is up and when i type the cmd dosent show any message

brazen raft
# patent wagon Security wise

Don't let them run arbitrary Python code like in eval or in exec and preferably limit their access to the internet

tidal hawk
slate swan
tidal hawk
#

Does it print without persistent views on ready?

slate swan
#

PLEASE HELLPP

slate swan
tidal hawk
#

No error? xd

vocal snow
slate swan
tidal hawk
#

Brruh

vocal snow
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
#

Dm me if you are a good developer

slate swan
vocal snow
tidal hawk
#

That's a lot of errors xd

slate swan
tidal hawk
vocal snow
slate swan
slate swan
vocal snow
slate swan
vocal snow
#

No

#

You need to enable message_content intent

#

You're only enabling members

slate swan
#

when i ping him like @slate swan it says but when i do other cmds they dont show

vocal snow
#

What

vocal snow
slate swan
#

where i type it

vocal snow
tidal hawk
#

is the bot online?

vocal snow
slate swan
unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

vocal snow
#

I'm not asking or offering paid work

slate swan
tidal hawk
#

isn't your async def on_ready indentation fked?

slate swan
#

good??

vocal snow
# slate swan

message_content not members intent why aren't you understanding this

slate swan
#

but that code is in my code

tidal hawk
#

it's on the same line as def init

slate swan
#

I dont know python

#

i just want to do a license bot...

tidal hawk
#

no? xD

vocal snow
slate swan
vocal snow
#

There are many free courses online, you can take one

slate swan
#

is that the whole ss ?

vocal snow
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

#

Hey @slate swan!

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

vocal snow
#

Ayo spoonfeeding isn't allowed here

slate swan
vocal snow
#

Yeah so teach him, don't spoonfeed

slate swan
#

Then they need to learn basics.

#

so is the code good

tidal hawk
#

xD

slate swan
#

no

#

the pastebin one

#

what i need to do from that code

#

this is the only message it can send

#

You have only shown the main file, not all the others (please don't though). You need to really contact the owner of the bot or read its documentation to understand it better, there shouldn't be any reason to change anything if you have downloaded it from GitHub.

tidal hawk
#

Google it how to manipulate a picture like that, and then implement it on Discord bot

brazen raft
#

Just so you know, instead of

async def petpet(ctx, *, member: discord.Member = None):
    member = member or ctx.author
    ...

you can do

async def petpet(ctx, member: discord.Member = commands.Author):
    ...
#

Also line 3140 is unnecessary and I don't know how gen_petpet nor how generate_image are implemented so I can't help if they are erroneous

tidal hawk
#

How many lines of code do you have @slate swan ?

brazen raft
#

I know, right? I would split my project into several files

tidal hawk
#

over 3500?

#

or is petpet the newest function in ur file?

#

Wtf

brazen raft
#

We can help

tidal hawk
#

over 4000?

#

Goddamnn

shut axle
#

How do I get the user's badges shown as emoji?

brazen raft
#

No

tidal hawk
#

How many modules have you imported? xd

#

Hahaha

#

It would take him a whole day to organize his functions into cogs xD

#

Try making it yourself first

#

mhm

slate swan
#

Just use asyncio.sleep with while true event

tidal hawk
#

He meant ratelimit ig

slate swan
#

Like

@bot.slash_command(name="stats")
async def stats(interaction: nextcord.Interaction):
#create channels stuff here 
while True:
   #update channels 
asyncio.sleep(5)```
tidal hawk
#

What?

slate swan
#

So it updates every 5 seconds (I think)

#

I can't remember time formatting for async

tidal hawk
#

You can only change the channel name 2 times in 10 minutes + you'd want to use tasks.loop for updating the channel names, no?

slate swan
#

My way would require less code

tidal hawk
#

So whenever bot does a restart then your method wouldn't work anymore

brazen raft
#

!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").
brazen raft
#

You need to store the ID of the channel somewhere in order to retrieve it in the function

#

If it's a single server bot, storing the ID in a bot variable is good enough

tidal hawk
brazen raft
#

It just calls a function that edits the category every now and then

#

That's how you would want to define the function for the task

#

Then store state channel IDs in a database of some sort and have the task go through each one and update it according to the channel's server

slate swan
#

plus a while loop? definitely not an option when you can use the async version for loops

tidal hawk
#

10 points for creativity

brazen raft
#

discord.py is back and booming

slate swan
#

plus it's py-cord not pycord. They are different libs

slate swan
brazen raft
#

You do you

tidal hawk
#

How many lines do you have in your bot main.py file? @slate swan has 4900+ 😎

slate swan
#

I know that it's a fork smh

#

Nextcord is best fork in my opinion

#

disnake is. end of discussion

brazen raft
#

What kind of bot commands

slate swan
#

Well do ctrl + f and search @bot.slash_command

slate swan
#

lmaao

#

smh

brazen raft
#

Well I don't know whether slash commands appear in bot.commands in pycord

slate swan
#

py-cord*

brazen raft
#

Right

#

That

slate swan
#

hyphens are cute ngl

tidal hawk
#

Did you follow the example correctly?

#

You also have to modify the Ticket view

#

Compare these two views and see if your have smth different

#

Send a picture of your ticket view

#

well well well

#

spot the difference

#

Also why is your ticket buttons in different classes?!

#

Yeah

#

Define a simple View that persists between bot restarts.

In order for a View to persist between restarts it needs to meet the following conditions:

1) The timeout of the View has to be set to None

2) Every item in the View has to have a custom_id set

It is recommended that the custom_id be sufficiently unique to

prevent conflicts with other buttons the bot sends.

For this example the custom_id is prefixed with the name of the bot.

Note that custom_ids can only be up to 100 characters long.

naive briar
#

What are you trying to do?

#

Use interaction.original_response to get the message

#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
naive briar
#

Eh yeah, you might have to use that instead 🥴

slate swan
torn sail
slate swan
torn sail
cold trout
#

hey, got a question, im having an error called "main() takes 0 positional arguments but 1 was given".

#

what is a positional argument?

slate swan
#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

they clearly mentioned that it's py-cord

torn sail
#

Nvm

cold trout
#

where should i go then

slate swan
cold trout
#

ok thanks.

whole sparrow
#

Has disnake completely migrated to slash commands or hasnt happened yet?

patent wagon
#

is it possibe to limit a function to only one server? lets say python code can somehow check if its in a certain server and then if it is in that server a command becomes available

austere vale
#
  #user dms bot
    #creating blocked user database
  @commands.Cog.listener()
  async def on_ready(self):
    self.bot.db=await aiosqlite.connect('blocked.db')
    await asyncio.sleep(3)
    async with self.bot.db.cursor() as cursor:
        await cursor.execute('CREATE TABLE IF NOT EXISTS blocked(user INTEGER)')
    await self.bot.db.commit()
    #block user command
  @commands.command()
  @commands.has_permissions(administrator=True)
  async def block(self, ctx, member:nextcord.Member,*,reason=None):
    async with self.bot.db.cursor() as cursor:
      await cursor.execute('INSERT INTO blocked VALUES(?)',(member.id))
    await self.bot.db.commit()
    await ctx.send(f'I have blocked {member.mention} from sending me messages for reason: {reason}')
    return

could someone help me with this error?

Ignoring exception in command block:
Traceback (most recent call last):
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\kouxi\Runa\cogs\moderation.py", line 121, in block
    await cursor.execute('INSERT INTO blocked VALUES(?)',(member.id))
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
ValueError: parameters are of unsupported type
fading marlin
#

discord IDs are BIGINT, not INTEGER

proven ore
#

any nice project ideas

fading marlin
patent wagon
#

is it possibe to limit a function to only one server? lets say python code can somehow check if its in a certain server and then if it is in that server a command becomes available

fading marlin
#

I just replied...

patent wagon
#

o

#

for some reason it didnt ping me

#

sorry

austere vale
#

also i have some other databases for leveling up and stuff, and it works fine with user being set to INTEGER?

fading marlin
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
fading marlin
#

probably the same thing

feral frost
#

you can also make it an ephemeral message

austere vale
#

im trying to create a database of a list of users so the bot can "block" them

when anyone dms the bot, the bot checks if their user id is in the table, and if it is, the function returns. if the id isnt in the table, the user isnt blocked, and the bot forwards the message to the mods in the server

feral frost
#

so it only shows up for the person who clicks it

fading marlin
#

that's against TOS

feral frost
#

i dont think it can but idk

fading marlin
#

making your bot create invites to a server so that you can join it

austere vale
fading marlin
#

wdym "globalchat"?

fading marlin
#

no, I don't

austere vale
#

ah that fixed it, thank you so much

fading marlin
#

ah

slate swan
#

You can create invites but users can't join

#

Since bot invite link is only usable by other bots

manic wing
#

since when

slate swan
manic wing
#

and bots cant join unless an admin invites them

slate swan
#

Well that's true but my theory is if they could join servers they could use that link

manic wing
fading marlin
slate swan
manic wing
#

what

#

where did you hear this

fading marlin
#

a user can join with an invite created by a bot, wdym

slate swan
manic wing
#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

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

Yup that's it

feral frost
#

hey @slate swan i have an answer to your question of joining servers your bot is in

manic wing
#

if i sent you that invite

#

you wouldnt be able to join?

slate swan
manic wing
#

do you mind me sending you the invite?

slate swan
#

Nope try it

manic wing
#

can you send a screenshot of what happens when you try and click it

slate swan
#

Sure

manic wing
#

theory debunked 👍

feral frost
#

np

fading marlin
#

again, that's against TOS

#

which falls under rule #5

mossy jacinth
#

how can i add a user to the channel?

fading marlin
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

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

pass member as the target

mossy jacinth
patent wagon
#

import discord
from discord.ext import commands
import aiohttp

client = commands.Bot(command_prefix="y.",intents=discord.Intents.all())
TOKEN=no

@client.event
async def on_ready(): #remove later?
print('bot is ready')

@client.event
async def bruh(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url of a page) as r:
print(r)

client.run(TOKEN)

#

discord.ext.commands.errors.CommandNotFound: Command "bruh" is not found

feral frost
#

change the @client.event to @client.command()

patent wagon
#

o

#

tnx

feral frost
#

np

fading marlin
# mossy jacinth

you need a TextChannel instance, and using that instance you set the permissions

patent wagon
#

import discord
from discord.ext import commands
import aiohttp

client = commands.Bot(command_prefix="y.",intents=discord.Intents.all())
TOKEN=no

@client.event
async def on_ready():
print('bot is ready')

@client.command()
async def bruh(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url of a page) as r:
print(r)

client.run(TOKEN)

#

how do i print the html of a page

#

im trying to webscrape but people have told me that "requests" module should not be used

fading marlin
patent wagon
#

that?

fading marlin
fading marlin
feral frost
#

you have to make a cooldown event

fading marlin
#

use an error handler to catch the exceptions

feral frost
#

for my slash bot it looks like this @tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(error, ephemeral=True) else: raise error

patent wagon
fading marlin
feral frost
#

ok

#

i use this in my text bot @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandOnCooldown): cd = round(error.retry_after) minutes = str(cd // 60) seconds = str(cd % 60) embed = discord.Embed(title="Oop, something went wrong!", description=f"Try this command again in {minutes} egg whites, and {seconds} egg yellows", color=color) embed.set_footer(text=footer) await ctx.send(embed=embed) if isinstance(error, commands.CommandNotFound): await ctx.send("I could not find that command. Use M.help to see al the commands.")

patent wagon
#

someting like that

feral frost
#

👌

fading marlin
patent wagon
#

ok tnc

#

also i think i did someting wrong

#

cos this is not working :

#

async def bruh(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as r:
await r.read()
print(r.read())

#

i think i misunderstood something

patent wagon
fading marlin
#

!d discord.ext.commands.Command.error you can use this to make a command-only error handler

unkempt canyonBOT
#

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

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
fading marlin
patent wagon
#

print(r.read())

fading marlin
patent wagon
#

i dont understand

fading marlin
patent wagon
#

so just await

#

when i did that it didnt print

fading marlin
patent wagon
#

not much

fading marlin
# patent wagon so just await

you don't just "await", you have to await SOMETHING, and that SOMETHING is r.read(), because r.read() is a COROUTINE, and COROUTINES have to be awaited

slate swan
#

I can send any code if needed

patent wagon
#

i do get that what i ment by "just await" was so just the await r.read()

#

bc it doesnt print it out

fading marlin
slate swan
#
import discord
from discord.ext import commands
intents = discord.Intents.default()

bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
    print("f Loaded.")

@bot.command()
async def hi():
    embed = discord.Embed(title="Elusive - API", color=discord.Color.from_rgb(0, 64, 255))
    embed.add_field(name="hi", value="hi", inline=False)
    embed.set_image(url="https://cdn.discordapp.com/attachments/971538759516581888/971585692016709663/ezgif.com-gif-maker_1.gif")
    await ctx.send(embed=embed)

bot.run("token is acc here just remvoed",bot=True)

none of the commands work not even the help command, no errors and it does print "f Loaded" on start

slate swan
fading marlin
fading marlin
fading marlin
slate swan
slate swan
fading marlin
fading marlin
# slate swan

same error, you've got 2 or more commands with the same name/alias

slate swan
slate swan
fading marlin
slate swan
#
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="$", intents=intents)
@bot.event
async def on_ready():
    print("f Loaded.")

@bot.command()
async def hi():
    embed = discord.Embed(title="Elusive - API", color=discord.Color.from_rgb(0, 64, 255))
    embed.add_field(name="hi", value="hi", inline=False)
    embed.set_image(url="https://cdn.discordapp.com/attachments/971538759516581888/971585692016709663/ezgif.com-gif-maker_1.gif")
    await ctx.send(embed=embed)

bot.run("token is here",bot=True)```
slate swan
fading marlin
slate swan
slate swan
#

in console tho ill check in vs code

#

PS C:\Users\User\Desktop\ELUSIVE-API> py a.py
Traceback (most recent call last):
File "C:\Users\User\Desktop\ELUSIVE-API\a.py", line 4, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'

fading marlin
#

update your dpy

slate swan
#

whats the command

fading marlin
slate swan
#

do i just pip install it again in a batch file

slate swan
fading marlin
slate swan
fading marlin
patent wagon
slate swan
#

hold on

fading marlin
fading marlin
fading marlin
patent wagon
patent wagon
# fading marlin traceback?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'method' has no len()

slate swan
#

read the error bruh

slate swan
#

print("")

patent wagon
# fading marlin send code

@client.command()
async def func(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results:

        doc = BeautifulSoup(results.text, "html.parser")

        await ctx.send(doc)
fading marlin
#

text is also a coroutine

#

and you gotta await coroutines

patent wagon
#

so how would it look like?

slate swan
#

i installed 3.10*

#

and i ran the command in terminal and it worked but same error

fading marlin
fading marlin
slate swan
#

i have 3.10 rn

fading marlin
#

use py -3 a.py then, otherwise you might be using python 2.7

patent wagon
#

@client.command()
async def func(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results:
await results.text

        doc = BeautifulSoup(results.text, "html.parser")

        await ctx.send(doc)
glad cradle
#

he can't use py 2.7, py >=3.8 is required

patent wagon
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object method can't be used in 'await' expression

slate swan
fading marlin
fading marlin
fading marlin
patent wagon
#

i dont fully get it

glad cradle
#

!function

unkempt canyonBOT
#

Calling vs. Referencing functions

When assigning a new name to a function, storing it in a container, or passing it as an argument, a common mistake made is to call the function. Instead of getting the actual function, you'll get its return value.

In Python you can treat function names just like any other variable. Assume there was a function called now that returns the current time. If you did x = now(), the current time would be assigned to x, but if you did x = now, the function now itself would be assigned to x. x and now would both equally reference the function.

Examples

# assigning new name

def foo():
    return 'bar'

def spam():
    return 'eggs'

baz = foo
baz() # returns 'bar'

ham = spam
ham() # returns 'eggs'
# storing in container

import math
functions = [math.sqrt, math.factorial, math.log]
functions[0](25) # returns 5.0
# the above equivalent to math.sqrt(25)
# passing as argument

class C:
    builtin_open = staticmethod(open)

# open function is passed
# to the staticmethod class
fading marlin
patent wagon
#

i dont have th epatience anymore

patent wagon
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object method can't be used in 'await' expression

#

can u just tell me

#

whats wrong

glad cradle
patent wagon
#

ill leave server and never ask nother time for help

fading marlin
patent wagon
#

pls just ned the godamn suffe

patent wagon
#

dont know how

glad cradle
patent wagon
#

jesus fuck

#

ill pay u right now to tell me where i made a mistake

fading marlin
#

I'm literally telling you where you made a mistake

patent wagon
#

where

fading marlin
#

first of all, do you know what function I'm referring to?

glad cradle
patent wagon
#

this is bringing me pain

glad cradle
#

the problem is await results.text

patent wagon
fading marlin
#

you're not calling that function

#

you should be calling it

glad cradle
#

you're not calling the function, you're referencing the function

patent wagon
#

so results.text()

#

or?

glad cradle
#

yes

patent wagon
#

ok

glad cradle
#

don't forget the await

patent wagon
fading marlin
#

?

glad cradle
slate swan
#

same error after resintalling python

glad cradle
#

that's not a python error

slate swan
#

wrong ss

glad cradle
#

what you're doing in your code

slate swan
patent wagon
#

RuntimeWarning: coroutine 'ClientResponse.read' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
#

line 4 is the error

fading marlin
glad cradle
slate swan
slate swan
fading marlin
#

pip freeze iirc and search for discord.py

slate swan
#

1.73? i think

patent wagon
# fading marlin you're not awaiting `read`

async def Crispy(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(urlCrispy) as resultsCrispy:
await resultsCrispy.text()

        docCrispy = BeautifulSoup(resultsCrispy, "html.parser")

        await ctx.send(docCrispy)
glad cradle
fading marlin
slate swan
#

now it works

fading marlin
#

re run your code now

slate swan
#

`

#
2022-09-22 16:40:24 INFO     discord.client logging in using static token
Traceback (most recent call last):
  File "C:\Users\User\Desktop\ELUSIVE-API\a.py", line 18, in <module>
    client.run("my token")
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 746, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 672, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
PS C:\Users\User\Desktop\ELUSIVE-API> ```
#

my actual token is there

glad cradle
#

Read the error

slate swan
#

im blind Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

Discord Developer Portal

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

patent wagon
# fading marlin you're not awaiting `read`

async def Crispy(ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get(urlCrispy) as resultsCrispy:
await resultsCrispy.text()

        docCrispy = BeautifulSoup(resultsCrispy, "html.parser")

        await ctx.send(docCrispy)
glad cradle
slate swan
glad cradle
patent wagon
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 4000 or fewer in length

glad cradle
#

you're trying to send a message that surpass the discord char limit

patent wagon
#

o frick

#

i tough i put it to print

#

ok

winged coral
#

I think that error body was quite informative by the way

#

They are usually quite helpful to read

mental hollow
#
    @commands.slash_command()
    @discord.guild_only()
    @commands.has_permissions(manage_messages = True)
    async def nick(
        self,
        ctx: discord.ApplicationContext,
        member: Option(discord.Member, "The user who's nickname you want to manage.", required = True, default = None),
        *,
        name: Option(str, "The new nickname of the user.", required = False, default = None)):
        try:
            await member.edit(nick = name, reason = default.responsible(ctx.author, "Changed by command"))
            message = f"**{member.name}'s** nickname was edited to **{name}**."
            if name is None:
                message = f"**{member.name}'s** nickname was reset."
            await ctx.respond(message)
        except Exception as e:
            await ctx.respond("An error occured, please contact support.")
            print("An error occured with the nick command: " + str(e))

Why is my member option coming up as optional when I set it to required?

winged coral
#

You set it to None by default

#

So no, it isn't required. If they don't provide it, it transforms into None

mental hollow
#

so what is it supposed to be by default?

winged coral
#

Remove the kwarg

#

Don't give it a default value

mental hollow
#

kk

#

works now, tyvm :)

winged coral
#

No worries!

sick birch
#

Yes but wrong channel

faint sapphire
#

k sorry

flint isle
#

how can I move a forum post from one channel to another in disnake?

patent wagon
#
    async with aiohttp.ClientSession() as cs:
         async with cs.get(url) as results:
            a =  await results.text()
            doc = BeautifulSoup(a, "html.parser")
            vallist = doc.find_all("span")
            status=vallist[0]

            await ctx.send(status)```
primal token
#

You shouldnt be opening a aiohttp session each time you invoke the command and you can always aiohttp.request so you dont nest context managers

#

!d aiohttp.request

unkempt canyonBOT
#
async-with aiohttp.request(method, url, *, params=None, data=None, json=None, headers=None, cookies=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', ...)```
Asynchronous context manager for performing an asynchronous HTTP request. Returns a [`ClientResponse`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse "aiohttp.ClientResponse") response object.
primal token
#

?

patent wagon
#

if i dont put async with aiohttp.ClientSession() as cs:
async with cs.get(url) as results: ont the beginning it doesnt worl

primal token
#

Just use the function given?

patent wagon
primal token
patent wagon
#

i am doing that?

primal token
#

Either way you should start a client session once and then use that session with aiohttp.ClientSession.request

patent wagon
#

and it chnages constantly

primal token
#

That still doesnt have any effect on each HTTP request

patent wagon
#

the code

slate swan
#
snipes = dict()

def snipe_embed(context_channel, message, user):
    if message.author not in message.guild.members or message.author.color == discord.Colour.default():
        embed = discord.Embed(description = message.content, timestamp = message.created_at)
    else:
        embed = discord.Embed(description = message.content, timestamp = message.created_at)
    embed.set_author(name = str(message.author), icon_url = message.author.avatar.url)
    if message.attachments:
        embed.add_field(name = 'Attachment(s)', value = '\n'.join([attachment.filename for attachment in message.attachments]) + '\n\nAttachment URLs are invalidated once the message is deleted.')
    if message.channel != context_channel:
        embed.set_footer(text = 'Sniped by: ' + str(user) + ' | in channel: #' + message.channel.name)
    else: 
        embed.set_footer(text = 'Sniped by: ' + str(user))
    return embed

class utility(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
    self.snipes = {}
    self.editsniped = {}

  @commands.Cog.listener()
  async def on_message_delete(self, message):
      if message.guild and not message.author.bot:
          try:
              snipes[message.guild.id][message.channel.id] = message
          except KeyError:
              snipes[message.guild.id] = {message.channel.id: message}

  @commands.command()
  @commands.cooldown(1, 3, commands.BucketType.user)
  @commands.guild_only()
  async def snipe(self, ctx, channel: discord.TextChannel = None):
      if not channel:
          channel = ctx.channel
      try:
          sniped_message = snipes[ctx.guild.id][channel.id]
      except KeyError:
          await ctx.send("There's nothing to snipe!")
      else:
          await ctx.send(embed = snipe_embed(ctx.channel, sniped_message, ctx.author))

I need help.. my snipe command isn’t working & it doesn’t send an error either. @primal token

primal token
# patent wagon then how should it look?

Just make an instance of aiohttp.ClientSession in something like setup_hook and use setattr to set an attribute of the newly made session and then you can use that

patent wagon
#

on that

#

im loosing my mind with this

primal token
#

No, it's just code structures.

slate swan
#

nice

untold iron
#

How can i make it so the user has to say yes to continue?

vocal snow
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.10)"). 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.10)") 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.10)") 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**...
vocal snow
#

You can wait for a message event

untold iron
#

Ahh thank you very much

#

i will try it out and see how it goes

#

Not sure what to input in the brackets though, is the client.command not an event though no?

#

How can i pass in a requirement for the words Yes or something?

vocal snow
#

Check the examples in the doc

untold iron
#

Ty

#

I try run this make channel command but it returns no object for the id?

#

File "c:\Users\wayed\Desktop\MerchantBot\bot.py", line 76, in make_channel
channel = await guild.create_text_channel('secret', overwrites=overwrites)

#

i think its something to do with my overwrites?

slate swan
#

why is this an error? do i need to import something? also this is a cog file idk if that matters

untold iron
#

Solved, my bad it was accessing a role tht wasnt there due to my spelling mistake on the role

frozen patio
#

I am in a cog, the starboard group commands are not working, and there is no errors. Why is that

slate swan
#

This is in a cog file do I need to import something or did i spell something wrong

frozen patio
#

the group doesn't exist

oblique loom
#

Please help, this is the code that I have

bot = commands.Bot(command_prefix=“.“)

It keeps returning this error

TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intent'

#

I’m not good with discord bots, and I’m still pretty new to python, and I just looked at some website to help me with this, please don’t judge

primal token
#

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

primal token
oblique loom
#

Thanks

#

Ok

#
[2022-09-22 17:52:37] [INFO    ] discord.client: logging in using static token
Traceback (most recent call last):
  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 ```
#

Now I’m getting this error

primal token
#

Your token must be a str

oblique loom
#

It is

#

What do I do? Make it not a string?

robust fulcrum
#

Guys is there any event in dpy that's gets triggered when my bot gets rate limited?

oblique loom
unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
oblique loom
#
Traceback (most recent call last):
  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 ```
#

Still getting this

oblique loom
#

@primal token

#

!d run

unkempt canyonBOT
#
run

run [args ...]``````py

restart [args ...]```
Restart the debugged Python program. If an argument is supplied, it is split with [`shlex`](https://docs.python.org/3/library/shlex.html#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.") and the result is used as the new [`sys.argv`](https://docs.python.org/3/library/sys.html#sys.argv "sys.argv"). History, breakpoints, actions and debugger options are preserved. [`restart`](https://docs.python.org/3/library/pdb.html#pdbcommand-restart) is an alias for [`run`](https://docs.python.org/3/library/pdb.html#pdbcommand-run).
slate swan
#

ImportError: cannot import name 'RequestsWebhookAdapter' from 'discord' (/home/container/.local/lib/python3.8/site-packages/discord/init.py)

#

fix?

vague zephyr
#

i'm stupid can't help sorry

wispy spade
wispy spade
#

I think it should give a bit more than that, but it does look like some other package is conflicting

slate swan
#

fixed it

vague zephyr
slate swan
#

it works, it works lmao

vague zephyr
#

it's not that hard to migrate

wispy spade
wispy spade
slate swan
#

i found this good hosting, that only charges 1.50 a month

vague zephyr
#

i use to host my bots on a raspberry pi

slate swan
#

you can't be using raspberry pi

vague zephyr
#

yeah i know

#

then i switched to ovh

slate swan
#

plox.host

#

best hosting

vague zephyr
#

oh yeah i heard of it

#

is it that good

slate swan
#

ive had no issues with it

rare echo
slate swan
vague zephyr
#

just like i have other stuff on my server so transferring all of it would be a pain in the ass

rare echo
vague zephyr
#

i do freelance shit and most of my clients are from france

primal token
vague zephyr
#

or neibhouring

#

so since ovh has pretty good servers there i never changed

#

until that incident when one of their data centers literally went on fire

slate swan
# slate swan plox.host

all I can think of the word "plox" is
please -> pls -> plz -> pliz -> plix -> plox
That's trust issues right there

#

Do you have any feedback?

#

Is the thumbnail redundant?

rare echo
slate swan
ionic garden
vocal snow
#

Inside the Bot subclass?

#

Why do you need it there pithink

primal token
#

Wouldnt recommend it, It's better to have it in a modular ext over having it in your Bot subclass which may clutter the whole class's structure and will not have the benefits of something like reloading a commands state.

ionic garden
#

ok, but is it possible

vocal snow
#

Yes

#

You'll need to use self.tree.add_command or whatever the method is to register it

ionic garden
#

oh ic

#

ok yeah i'll just stick w/ the og

kind trellis
#

How can I reload a YAML file without having to restart the bot?

vocal snow
#

What do you mean reload a yaml file

kind trellis
#

Like how you can reload a cog

#

I want to do that with a YAML file

vocal snow
#

Those are two very different things

#

If you want to just re-read the yaml file then just re-read the yaml file

kind trellis
#

How? I tried that and the bot just reads the cached old version anyway

vocal snow
#

How are you re-reading it?

kind trellis
#

Hang on

rugged shadow
#

we're hanging on

#

we are about to fall off the cliff

#

don't leave us here

kind trellis
#
    @commands.command(name='reload', hidden=True) 
     @commands.is_owner() 
     async def _reload(self, ctx, *, cog: str): 
         """Command which Reloads a Module. 
         Remember to use dot path. e.g: cogs.owner"""
        if cog == 'yaml': 
             await ctx.send('**`Reloading YAML file...`**') 
             try:           
                 with open("/home/pi/Documents/Room_Sealer/groups.yaml""r"as f: 
                     self.bot.channelgroups = yaml.full_load(f) 
                 await ctx.send('**`Reloaded YAML file`**') 
             except Exception as e: 
                 await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')```
#

@vocal snow

vocal snow
#

And what uses self.bot.channelgroups?

kind trellis
#

The main file

vocal snow
#

Can you share the code the uses it

kind trellis
#
@bot.command(name='seal') 
 @commands.guild_only() 
 async def _seal(ctx): 
     if ctx.channel.category_id in channelgroups['non-rp']: 
         await ctx.send(':x: | This command can only be used in rp!') 
         print(f'Command r!{ctx.command} used in a non-rp channel by {ctx.author.name}') 
     elif ctx.channel.category_id == 741756076126634076: 
         await ctx.message.delete() 
         await ctx.send('(Wrong command! `r!rp-set-seal` or `r!rp-set-unseal` is the correct ones to use)', delete_after=7) 
         print(f'Command r!{ctx.command} used in a general rp channel by {ctx.author.name}') 
     elif ctx.channel.category_id in channelgroups['ships']: 
         await ctx.message.delete() 
         await ctx.send('(Ships cannot be sealed by the bot. Use [#741756142916468868](/guild/267624335836053506/channel/741756142916468868/), [#747578010278035536](/guild/267624335836053506/channel/747578010278035536/), [#741756219064189029](/guild/267624335836053506/channel/741756219064189029/), [#745682027667390505](/guild/267624335836053506/channel/745682027667390505/), or [#741756303814426768](/guild/267624335836053506/channel/741756303814426768/).)', delete_after=7) 
         print(f'Command r!{ctx.command} used in a ship channel by {ctx.author.name}')```
vocal snow
#

This is using channelgroups

#

Not bot.channelgroups

kind trellis
#

Reeeeee

#

So, bot.channelgroups will 100% work?

slate swan
#

well yes

kind trellis
#

Ok, I'll make the fix when I wake up

primal token
#

Not sure what youre trying to do exactly but i do feel that this should addressed, with open will block the event loop as its not scheduling the task of a function, it's not really an issue as it wont block the event loop for much time but it's good practice to open a file asynchronously so you dont face any weird behaviors or speed related issues.

kind trellis
#

It's never going to be on a task

kind trellis
slate swan
primal token
kind trellis
#

Noted

primal token
slate swan
#

yep still pretty bad wording there

primal token
#

Can you please enlighten me?

slate swan
#

here'a a simpler explanation: open() is a blocking IO call, you should probably use an async variant of the function to avoid blocking the event loop.

slate swan
meager chasm
#

"as its not scheduling the task of a function" what that even eman xdd

primal token
slate swan
#

you don't schedule a function to the event loop...

primal token
primal token
slate swan
#

your explanation is simply too long, it can be shortened without losing information.

slate swan
#

it's not the same

primal token
#

What?

slate swan
primal token
slate swan
#

a coroutine object is not a function (or callable, for a better term)

slate swan
slate swan
primal token
primal token
shrewd apex
vocal snow
#

Wdym preoccupied

#

You shouldn't have blocking code

vale wing
#

I can't read C

#

Especially cython extensions

glad cradle
#

AFAIK when you have blocking code the connection on between the Bot and discord websocket receives a delay, this delay accumulates until the Bot disconnects from the websocket due to the delay, if the library you are using implements a resume logic then the library will try to reconnect.
Events dispatched between the resume operation are lost, your Bot will not receive them, instead when the bot is behind the discord websocket the bot will perform the functions associated with event dispatches delayed

slate swan
#

wdym by “preoccupied”?

#

you mean a blocked event loop?

glad cradle
#

if the resume start on (bot blocked) it should receives a, b, e

btw the bot doesn't do resume when it's blocked, it'll try to resume the session when it's disconnected from the discord ws

the delay between discord ws and your Bot leave some messages sent by Discord unanswered, or rather, the replies your Bot sends them late, sometimes too late and then discord will disconnect your Bot thinking it is dead

slate swan
#

that’s no good... you should avoid doing that or just don’t use an async library

primal token
#

just dont?

#

you mean use an async library?

slate swan
#

can you give an example of what you’re trying to do that causes ur bot to enter this blocked state?

#

yep, you should use asyncio’s networking implementation

#

hm

#

what is “Stream”?

#

you use await reader.read(...)

#

well yeah i know what you mean now

glad cradle
#

Bot B receives data, so how it can't know? that depends on how Bot B dispatch custom events

slate swan
#

referring to it as “Stream” is way too vague

#

yes, you can use loop.create_task()

#

i mean a little context would be nice, “asyncio streams” makes more sense to me

#

yep

#

asyncio.get_running_loop() should be sufficient

#

i mean you can read the source for yourself if you want

#

and this is how the on_message event is dispatched, for example

#

self.dispatch is a bound Client.dispatch method

#

discord.py internals are pretty terrible, trying to read it is a nightmare

#

👍

glad cradle
primal token
#

The whole codebase should be restructured

robust fulcrum
#

Guys is there any event in dpy that gets triggered when bot gets rate limited?

vale wing
#

Because it might occur in listeners, on_command_error is not really suitable

vale wing
#

It's a method of commands.Bot as I said

robust fulcrum
vale wing
unkempt canyonBOT
#

utils/bot.py lines 106 to 108

async def on_error(self, event_method: str, *args, **kwargs):
    self.log.error("Unhandled exception occured at %s", event_method)
    await self.log_error()```
robust fulcrum
#

I mean the on_error method

slate swan
#

lol i mean if you think http.py is bad, you haven't seen the commands extension

#

honestly at this point i'm gonna start listing out all the files

robust fulcrum
vale wing
#

And the error is not necessary the HTTPException with 429 code

#

!d sys.exc_info you get the exception itself via this

unkempt canyonBOT
#

sys.exc_info()```
This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.
vale wing
pulsar solstice
#

how to save my 8ball command responce in cache that the response of a question never changes.

#

then if u ask a same question to the bot again and again it should always give the same answer

vale wing
slate swan
#

#bot-commands

robust fulcrum
vale wing
#

You should

robust fulcrum
vale wing
#

That's a helpful skill for a programmer

robust fulcrum
#

Ok

robust fulcrum
#

how to restart my bot?

vale wing
#

Personally I'd do it with shell script

slate swan
pulsar solstice
placid skiff
#

The cache is just a volatile type memory, it is handled by the processor of the machine
When we say that a data is stored in the cache it means that in that specific instance of a process you can access that data
When you declare a variable for example, it is not allocated in the memory permanently, the portion of memory that needed to be stored by a variable will be allocated only during the runtime of your program. Once the program finish the data will not physically exist anymore
So to do that, you only need to create a dict inside of your program, accessible everywhere in your code, and the trick is done D_D

rugged shadow
#

you don't have to say all that

placid skiff
#

He was confused about what is the cache, we're here to help people learn. I've just explained him how cache and runtime memory works, those things are not useless as they appear

rugged shadow
#

you were talking about the low-level cache

#

the very low-level one

#

you could've just said "make a dict and set it to the first response of that question"

placid skiff
#

Ashley told to him and he didn't understand D_D
That means that he needed an explanation D_D

placid skiff
vale wing
#

Also docs reading

#

But they come from google

#

So yeah you are right

vale wing
pulsar solstice
vale wing
#

Yes like that

slate swan
#

when you use get_guild, get_member etc, dict.get is called for those objs

vale wing
#

For example you want a set of records from database with very complex condition, large database and small amount of records you actually need, you can just fetch them once from database and use

pulsar solstice
vale wing
#

Although in case of database you might need to do the data syncing properly, this is not your case

slate swan
#

and whenever you need the results you can do ```py
dictionary [key] # raises an error if key is not in dictionary

or

dictionary.get(key) # returns None if key is not in dictionary

pulsar solstice
#

so u mean this is okay?

#

and btw it works

slate swan
#

yep seems fine to me

pulsar solstice
#

:\

slate swan
#

in this case, yes

#

a dictionary can be used as a cache

pulsar solstice
placid skiff
#

nope, but you can store all sort of data types in the value, even lists, sets, tuple or another dict

pulsar solstice
slate swan
slate swan
pulsar solstice
slate swan
#

or preferably a dataclass for easier accessibility

#

oh wait tvrsier said that already

slate swan
#

value*

slate swan
pulsar solstice
slate swan
pulsar solstice
placid skiff
#

nope i still haven't got it yet D_D

placid skiff
#

so you mean you have this for example

pulsar solstice
#

how should I tell u!!

#

bruhmy barin

#

ahhhhhhhhhhhhhhh!!!

pulsar solstice
placid skiff
#
pokemon = {"pikachu": {"name": "pikachu", "type": "electro", "moves": ["thunder", "quick attack", "electro ball", "double team"]}, ...}
```?
drifting arrow
#

Anybody ever worked with music bots?

vale wing
#

Yes and it wasn't a pleasant experience

drifting arrow
shrewd apex
#

i did 👀

drifting arrow
shrewd apex
#

i think streamed the audio

#

i*

drifting arrow
#

Can you send the code? I give up on trying to google solutions. everythings all wrong, not even the discordpy example works

shrewd apex
#

well yeah downloaded but not saving locally ig idr

drifting arrow
#

im doing that D:

#

youtube_dl? correct?

#

or is it actually ytdl?

shrewd apex
#

i used ytdl and ffmpeg before it was banned 👀

robust fulcrum
#

Guys how i can use local image in the embed?

drifting arrow
shrewd apex
#

use SoundCloud ig

robust fulcrum
spare urchin
#

how would you add cooldowns for slash commands in nextcord??

faint sapphire
#

wassup, is this how i make a function run once an hour, to allow bot commands to work meanwhile

async def checkUserExists(userID):
    while True:
        asyncio.sleep(3600)
        runFunc()
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").
slate swan
faint sapphire
#

ok thanks

robust fulcrum
slate swan
#

put the url as

url="attachment://image_name.ext"```
robust fulcrum
#

Ok

slate swan
grand willow
#

What can I do if the content it wants to send is to big is there a way to split it into more than 1 Message and then send those

faint sapphire
#

does this seem right```py
@discord.ext.tasks.loop(hours=1, reconnect=True)
async def compareUpdates(ctx):
runFunc()

naive briar
#

If you need ctx in it, ye

faint sapphire
#

i dont

#

seems to be correct otherwise ig

naive briar
#

Then don't pass ctx in the parameter

faint sapphire
#

ight thanks

drifting arrow
#

;D

tidal hawk
#

What is the base url for Discord bot API endpoints?

#

For example for this ☝️

naive briar
tidal hawk
#

Thankss

slate swan
#

So I was in the callback of a view, and I tried to do interaction.edit_original_message(...), but then I got an Invalid Webhook error, any idea why?

#

how do u install requirements again

gaunt ice
drifting arrow
#

😦

glad cradle
slate swan
#

How to defer it?

glad cradle
#

iirc for d.py should be interaction.response.defer()

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
robust fulcrum
#

Guys do we need application.commands scope to make slash commands work?

naive briar
#

Yes

sly fog
#

why doesn’t bot.tree.command work

#

AttributeError: 'SlashBot' object has no attribute 'tree'

#

it gives me this error

mossy jacinth
sick birch
naive briar
# mossy jacinth

You have to pass the overwrite as nextcord.PermissionOverwrite not dictionary

overwrite = nextcord.PermissionOverwrite(...)

await c.set_permissions(member, overwrite=overwrite)
await c.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await c.set_permissions(ctx.guild.me, overwrite=overwrite)

If you want to set the overwrite for multiple roles or members, you have to set it individually

robust fulcrum
#

Guys how can I make a system that when my bot gets rate limited it types kill 1 in the shell?

slate swan
#

!d os.system use this

unkempt canyonBOT
#

os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
limber bison
#

how can i disable command in a pertucular server ?
i dont think command.update(enabled=False) will work it will disable for all 😳

robust fulcrum
vale wing
vale wing
limber bison
#

damn

vale wing
#

As you wish

limber bison
vale wing
#

If it is long-term storage there's no other option

#

If you don't want it to be persistent between bot runs then just put it into some dict

robust fulcrum
vale wing
#

When you shutdown the bot just os.system("kill 1") is most likely gonna kill the bot itself and no other instructions will continue, so you need to either use the shell script so all the commands you need get executed correctly, or something like kill 1 && python3 main.py

#

But the most simple thing to do to accomplish this is basically don't fricking use replit

robust fulcrum
robust fulcrum
slate swan
robust fulcrum
slate swan
#

not using replit is the best one

#

you can use pydroid or termux to run your code

robust fulcrum
#

Idk how to use it

slate swan
#

just download your files, pip install the requirements
and use python filename.py

robust fulcrum
#

In pydroid?

#

Pydroid terminal is bad

slate swan
#

*i don't know how to use it

ivory cave
#

how can i make it so that when the bot sends a link its clickable

#

?

slate swan
ivory cave
#

there was this one time yesterday, i my bot sent a valid link that if copy pasted into google was valid but the link itself wasnt clickable

#

i cant recreate it right now

#

ah wait, i think i figured it out nevermind

slate swan
#

you probably forgot to add http/https

vale wing
#

I don't know how to explain it any clearer without spoonfeeding

slate swan
#

overriding on_error can be very risky, make sure you don't end up eating other errors

vale wing
#

Yeah make sure to always print the traceback

#

And yeah the traceback object is the third value in tuple returned by exc_info

limber bison
#
@client.listen()
async def on_guild_join( guild):
        await db.create_collection(name= str(guild.id))
      
async def on_message(message):
        if message.author == client:
            await message.channel.send(client)
            return

        if message.content == 'ok':
            await message.channel.send('Hello World!')```
#

why this not working ?

#

any idea

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

(main.py)

@bot.command()
async def usluga(ctx):
    view = ticket()
    embed=disnake.Embed(title="Zamów usługę :bell:", description="Wybierz kategorię usługi, która Cię interesuje", color=0xae00ff)
    await ctx.channel.send(embed=embed, view=view)```

(cogs--->ticketSystem.py)
#

what's problem

ivory cave
vocal snow
slate swan
mossy jacinth
faint sapphire
#

anyone used asyncpg
its recommended in a discord.py github post for background tasks

but apparently i need to add a C compiler, unless if i have a recent pip version, which i do, import could not be resolved persists
https://magicstack.github.io/asyncpg/current/installation.html

or is this useless anyway, what i do is that each hour it does webscraping and compares it to whats in the db

tall swallow
#

Can anyone help me with my bot verification?

vestal dagger
tall swallow
#

I want verify my bot, it's asking for a tos and i need help for it

vestal dagger
tall swallow
#

It's not an error

feral frost
#

Question:
How can i check for a message in a normal command like this and than print it?

                return message.author == ctx.author and message.channel == ctx.channel and message.content.lower() == message```
vale wing
#

You need C compiler only to build it from source

glad cradle
faint sapphire
#

importing it is like i didnt install it

#

i removed it and tried again too

vale wing
#

Are you sure you install it into the correct environment and run the script from the same environment

faint sapphire
#

i dont use venv, i did it from the vs code terminal

vale wing
#

How many python versions do you have installed

faint sapphire
#

no idea lol
all i know is that python isnt a command, so i guess i have just python 3

#

i have 3.10.5 for py3

vale wing
#

Using venvs is a good practice and helps to avoid these cringe PATH issues

#

Create a venv via python3 -m venv venv and select the new interpreter from command pallet (CTRL + SHIFT + P -> Select Interpreter)

faint sapphire
vale wing
#

Just create a new venv for new project

#

That's what every good developer does

faint sapphire
#

ight then

vale wing
#

When you install many global packages they might start having dependencies conflicts

#

So better to have everything isolated

slate swan
#

hey anyone able to help me make my first discord bot?

faint sapphire
#

tho ive been using them for 1 proj so far

#

then i gotta remove them for future stuff

vale wing
#

As for your case, you most likely have several python versions installed, and you pip install with one, but run the script with another

#

Venvs help to avoid that too

faint sapphire
#

ok, thanks

primal token
unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

primal token
#

you can also use poetry for envs

#

!pypi poetry

unkempt canyonBOT
honest shoal
#

what is num_range

faint sapphire
#

i got the locked error from sqlite3
should i consider a diff db, or is it ight to make one connection like this and use it over time
also, if I do that, do i set the cursor each time and close it?```py
@bot.event
async def on_ready():
if bot.db_con is None:
bot.db_con = bot.db_con = await aiosqlite.connect("database.db")

teal mesa
#

whats the code so no one can DM my discord bot? and where do i put it.

teal mesa
faint sapphire
#

idk, why would u worry ab that

sick birch
teal mesa
sick birch
#

I know, same deal with your bot

primal token
#

iirc you can just not set the dm unprivaliged intent

teal mesa
sick birch
#

Just ignore DM channel messages in your on message with conditional process commands

faint sapphire
#

im sure ur premium members are in a databse

#

u can just look if they in it

primal token
#

A check would be enough

teal mesa
#

BROOOOOOOOOO

#

idc about what u guys say, can you just tell me the code

#

i have been looking EVERYWHERE

faint sapphire
stark brook
#

guys hwo have code that give user a a role for set time

faint sapphire
teal mesa
#

the server is about this predictions bots, i want the script so thay will type commands in chat and be active. it defeets the whaol ting if i have a dead chat and thay are in bots dm

faint sapphire
#

so like a task loop or cog

teal mesa
stark brook
faint sapphire
#

then u check if the user has premium

#

to see if u allow them to use commands

#

so u search in ur database

#

cause u obviously use one for remembering who has premium

primal token
faint sapphire
primal token
#

kek

faint sapphire
#

this was supposedly a solution to the locked error
but i still get it, am i supposed to create a cursor and close it each time? (i do btw)
(https://stackoverflow.com/questions/73416313/whats-making-this-code-lock-my-aiosqlite-database)

edgy tundra
#

how to set that
like

Prefix for your server is -----

#

in bot for custom server prefix

primal token
edgy tundra
teal mesa
primal token
faint sapphire
teal mesa
#

like this

runic nova
primal token
#

Why are you making an instance of Intents but not using it?

slate swan
#

Hey guys! So i want to know that i want to make an command that tells you howmuch time your bot has been on. could someone help me?.

slate swan
honest shoal
slate swan
#

No , I want it by a script.

teal mesa
#

its not mine, i wanna have it like he does

slate swan
#

under async

honest shoal
slate swan
#

I want it that it calculates by its self when using an command .info

honest shoal
#

not possible, you have to store it when the bot starts

#

¯_(ツ)_/¯

slate swan
#

How do you store it.

#

Sorry im a bi tdumb.

honest shoal
#

in a variable most likely

#

or database

#

just store the current time when the bot starts and when .info command is used then from current time again subtract the time you stored

slate swan
#

Thanks.

primal token
# honest shoal or database

it's better to store the time inside of on_connect if your bot isnt HTTP only and bind the value to the instance of your bot

honest shoal
#

oh, I forgot about on_connect completely

primal token
feral frost
#

anyone knows a simple easy way to make an eval command ?

primal token
feral frost
#

ok

primal token
#

That's what @unkempt canyon uses!

feral frost
#

ok

primal token
#

ok

sick birch
#

ok

feral frost
#

👌

kind trellis
# vocal snow Not bot.channelgroups

I just pushed this and I'm getting the same results. New categories added to the yaml file are not being recognized by the bot after an attempted reload

slate swan
#

Hi

feral frost
primal token
#

!src eval

unkempt canyonBOT
#
Command: eval

Run Python code and get the results.

Source Code
primal token
feral frost
#

k ty

kind trellis
#

@bot.command, @client.command or @commands.command

primal token
#

It would depend

kind trellis
#

On where you're doing it and how your previous lines of code are written

primal token
#

It would depend on your codebase and its structure, yes.

kind trellis
#

Btw, @primal token do you by chance know of a way to store info like category IDs into a file and have that file be reloaded easily via a command for if statements?

primal token
feral frost
#

Code:

import ast

def insert_returns(body):
    # insert return stmt if the last expression is a expression statement
    if isinstance(body[-1], ast.Expr):
        body[-1] = ast.Return(body[-1].value)
        ast.fix_missing_locations(body[-1])

    # for if statements, we insert returns into the body and the orelse
    if isinstance(body[-1], ast.If):
        insert_returns(body[-1].body)
        insert_returns(body[-1].orelse)

    # for with blocks, again we insert returns into the body
    if isinstance(body[-1], ast.With):
        insert_returns(body[-1].body)

@bot.command()
async def eval_fn(ctx, *, cmd):
    fn_name = "_eval_expr"

    cmd = cmd.strip("` ")

    # add a layer of indentation
    cmd = "\n".join(f"    {i}" for i in cmd.splitlines())

    # wrap in async def body
    body = f"async def {fn_name}():\n{cmd}"

    parsed = ast.parse(body)
    body = parsed.body[0].body

    insert_returns(body)

    env = {
        'bot': ctx.bot,
        'discord': discord,
        'commands': commands,
        'ctx': ctx,
        '__import__': __import__
    }
    exec(compile(parsed, filename="<ast>", mode="exec"), env)

    result = (await eval(f"{fn_name}()", env))
    await ctx.send(result)```
**Error:**
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
kind trellis
primal token
#

!pypi aiofiles | it's a library that manages files asynchronously

unkempt canyonBOT
feral frost
#

I have a problem with this code it says smth about empty message

kind trellis
#

Your result didn't output anything

#

Try printing the await eval part first

feral frost
#

? how

feral frost
untold iron
#

Whenever i run this command to create a private channel, it ends up looping infinitely ?

#

@client.command()
async def make_channel(ctx):
    guild = ctx.guild
    member = ctx.author
    admin_role = get(guild.roles, name="Admin")
    channelname = 'Seceret'

    mbed = discord.Embed(
    title = 'Success',
    description = "{} has been successfully created.".format(channelname)
    )

    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(read_messages=True),
        admin_role: discord.PermissionOverwrite(read_messages=True)
    }
    channel = await guild.create_text_channel(name='{}'.format(channelname), overwrites=overwrites)
    await ctx.send(embed=mbed)
    test1 = await channel.send(embed=await make_channel(ctx))
    await channel.send(embed=await IndicatorSale(ctx))
    await test1.add_reaction(NReact)```
faint sapphire
feral frost
# untold iron ```py @client.command() async def make_channel(ctx): guild = ctx.guild ...
async def make_channel(ctx):
    guild = ctx.guild
    member = ctx.author
    channelname = 'Seceret'

    mbed = discord.Embed(
    title = 'Success',
    description = "{} has been successfully created.".format(channelname)
    )

    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        member: discord.PermissionOverwrite(read_messages=True),
    }
    await guild.create_text_channel(name='{}'.format(channelname), overwrites=overwrites)
    await ctx.send(embed=mbed)````might be a little bit different but the problem was in the (channel = await guild.create....)
untold iron
#

Yes thank you very much

feral frost
#

np 🙂

untold iron
#

i saw my silly mistake, i was basically embedding the same channel made lol