#discord-bots

1 messages · Page 126 of 1

loud junco
#

u know any?

slate swan
slate swan
#

you wanna learn how to use a database
or you already do and want to host one

loud junco
#

i already know how i just need to host

slate swan
#

and then use any you want to

slate swan
loud junco
#

aight thanksss

slate swan
#

My extension fails to load, and I don't get any errors. Any ideas why?

#

How do i make a changing status loop?

placid skiff
#

do you have any error handler? @event async def on_error

placid skiff
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
#

Tyyy

slate swan
#
ie = []
for i in os.listdir("./cogs"):
    if i.endswith(".py"):
        ie.append("cogs." + i[:-3])
        
if __name__ == '__main__':
    for ex in ie:
        bot.load_extension(ex)

    bot.loop = asyncio.get_event_loop()
    bot.loop.run_until_complete(_startbot(bot))
    a = '\n'.join(i for i in bot.extensions)
    print(f"Loaded Extensions:\nNote that there should be:\n- modmail\nList:\n {a}")

Then in the terminal:

Loaded Extensions:
Note that there should be:
- modmail
List:
 


-------------------------------
You are logged in as Testing#3233!
#

And the default help message only says this: Nothing about the modmail cog.```
No Category:
help Shows this message

Type >help command for more info on a command.
You can also type >help category for more info on a category.

naive briar
#

What the

placid skiff
#

first of all check if the ie list contains something, maybe it doesn't find the directory
then add your extensions with this code, it will help with errors:

for cog in cogs: #cogs is the list where extensions are stored
  try:
     print(f"loadin {cog}")
     bot.load_extension(f"path/to/cogs/{cog}")
  except discord.ext.commands.NoEntryPointError as e:
      print(f"Ignoring exception in loading cog: {cog}\nNo setup found", file=sys.stderr)
      traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
  except discord.ext.commands.ExtensionFailed as e:
      print(f"Ignoring exception in loading cog: {cog}\nThe extension or its setup had an execution error", file=sys.stderr)
      traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
   else:
      print(f"{cog} loaded")

remember to import sys and traceback

upbeat gust
#

why make all this unnecessary code

upbeat gust
placid skiff
slate swan
#

It worked an hour ago tho

upbeat gust
#

probably bc you updated dpy

placid skiff
#

and that is nicer than the default logging

upbeat gust
#

Your extension loading is also outdated btw

placid skiff
#

well nope, not for disnake D_D

slate swan
slate swan
#

I'm using py-cord too

#

Found the problem

#

It didn't give me an error, but when I printed the result it contained the error. 🤷‍♂️

placid skiff
#

lol

slate swan
#
            a = bot.load_extension(f'cogs.{filename[:-3]}')
            print(a)
```Gave this in console```
{'cogs.modmail': ExtensionFailed("Extension 'cogs.modmail' raised an error: SyntaxError: positional argument follows keyword argument (modmail.py, line 46)")}
#

Another one, what does this means?```py
{'cogs.modmail': ExtensionFailed("Extension 'cogs.modmail' raised an error: SyntaxError: EOL while scanning string literal (functions.py, line 16)")}

placid skiff
#

The errors are in your modmail file, line 46 and functions file, line 16

slate swan
#

But if I have an error in the functions file, why doesn't the modmail file load? The error didn't show up in console at first, and the bot still starts.

placid skiff
#

loading cogs doesn't stop the bot from starting, it will just run without the extension

#

and it can be because your modmail use some methods of the functions file

slate swan
#

Ah

#

Alright! Thanks!

serene lynx
#

bro, what is the order system for the voice channel?

#

join to create position is 69 and 384 position is 72

lofty lance
#
        for i in range(len[feilds]):
            a = feilds[zer]
            a.split(':')
            ke = a[0]
            val = a[1]
            embed.add_field(name=ke, value=val)
            zer = zer + 1

#

in this i am trying to get data from a dict and send it in feilds of embed

#

dict = {em_feilds{key 1:" hi this is key 1 ",key 2:" hi this is key 2"}}

#

this is what i am trying to send but it shows me error :

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'builtin_function_or_method' object is not subscriptable

#

this is the error i am getting

primal token
#

!e

print[0]
unkempt canyonBOT
#

@primal token :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'builtin_function_or_method' object is not subscriptable
slate swan
#

How can I send all errors to a text channel? Using on_command_error I only get the errors in commands, not the ones like missing permissions and events stuff.

#

how to make my bot send embed messages?

lofty lance
slate swan
lofty lance
#

still learing

slate swan
#

can you tell me the basics please?

lofty lance
#

i learnd it from api

slate swan
#

the docs?

#

I will check it out then

upbeat gust
#

starting from scratch or a working bot

slate swan
#

but I am not new to python overall

upbeat gust
slate swan
#

ty peeps

upbeat gust
#

Check out webhooks

slate swan
#

I used them before

#

I want embed messages to make my bot seem more clean

#

why is it sending it twice

upbeat gust
novel apexBOT
#

This is not a Modmail thread.

upbeat gust
#

ah this isnt dpy

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.

slate swan
# upbeat gust
@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.CommandNotFound):
    await ctx.reply("❌ We dont have that command ! Try using !help")
  else:
       raise error```
upbeat gust
#

?

slate swan
#

thats the code

#

how is that wrong

upbeat gust
slate swan
upbeat gust
slate swan
#

Help bro

#

@upbeat gust

upbeat gust
#

I can't read your mind

slate swan
#

It dont work

#

to_rgb

upbeat gust
upbeat gust
slate swan
upbeat gust
#

You should be using the from_rgb class method of discord.Colour

slate swan
#

@upbeat gust

slate swan
#

Why only to_rgb?

slate swan
#

@upbeat gust

upbeat gust
#

I strongly recommend you familiarise yourself with oop

slate swan
#

ITS GETTING WORST WHAT

upbeat gust
upbeat gust
#

How do you know?

slate swan
#

also i have that command

slate swan
#

what is going on

#

do i need to update my vscode?

upbeat gust
upbeat gust
slate swan
slate swan
tired pine
#

say_msg: str = None??

naive briar
#

That's the default value

tired pine
#

also idk what nextcord is lol

#

I know discord.Embed

#

Idk wth is nextcord.Embed

naive briar
tired pine
#

also if you want parameters just use bot.tree.commands for slash commands

#

it's easier and looks cooler

slate swan
#

im using nextcord

upbeat gust
tired pine
#

if you need further help with discord.py join gg/dpy

slate swan
#

like they have a lot of customers

#

ill try to open a ticket

#

maybe they could help

tired pine
upbeat gust
tired pine
#

my bot has a /say command

#

and it works perfectly

slate swan
tired pine
slate swan
#

but the hosting

#

idk maybe its bc of them

tired pine
#

you use vs code right?

slate swan
#

yes

upbeat gust
tired pine
#

then it will show an error message in the terminal if it's because of them

upbeat gust
#

???

#

your editor has nothing to do with the hosting

#

There wouldn't even be an error in the case

tired pine
#

If the bot is not online and you use a slash command it will show an error

naive briar
#

Guh!?

upbeat gust
#

Who asked though

#

That's completely irrelevant

slate swan
#

ok its a problem w my code

#

i reset the token

#

so these are my packages

import nextcord
from nextcord.ext import commands, tasks
from nextcord import Interaction
from nextcord import File
import asyncio
from nextcord.ext.commands import cooldown, BucketType
from nextcord.ui import Select
import datetime
import random
from datetime import datetime, timedelta
from nextcord.abc import GuildChannel
from nextcord import slash_command
import humanfriendly
import calendar
from random import randint
import os

maybe some of them got updates?

upbeat gust
#

99% sure it's your hosting

slate swan
slate swan
#

so theres no way

upbeat gust
#

Ok then

#

I can't help with nextcord

vocal plover
#

@slate swan have you loaded the extension/cog that command is in? That's the only reason it wouldn't be being registered

slate swan
#

def setup(bot):
bot.add_cog(commands(bot))

vocal plover
#

and you're running bot.load_extension("your_ext_name") in the main bot file?

slate swan
#

for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
bot.load_extension(f"cogs.{fn[:-3]}")

vocal plover
#

Hmm, not sure then, probably worth joining the nextcord server for help on it, there's a help channel system there with lib-specific knowledge

slate swan
#

yes theyre trying to help

#

its so weird

#

should i do that

#

i did

#

and still doesnt work

spring summit
slate swan
#

wtf is wrong w my bot

#

i deleted a command and it still sending it

spring summit
spring summit
#

reset your token and retry, that might help

spring summit
slate swan
#

ill try again

spring summit
slate swan
#

yes but i closed it also changed tge token again

#

now its sending twice

#
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Noas Bot\main.py", line 155, in on_command_error
    raise error
nextcord.ext.commands.errors.CommandNotFound: Command "sadfhgsay" is not found
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Noas Bot\main.py", line 155, in on_command_error
    raise error
nextcord.ext.commands.errors.CommandNotFound: Command "sadfhgsay" is not found```
#

in the terminal and in the server

spring summit
slate swan
#

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

slate swan
spring summit
slate swan
#

what

spring summit
#

what command is causing the problem?

slate swan
#

everything

#

everycommand that it isnt slash command

hushed galleon
slate swan
#

yes!

#

a lot

hushed galleon
#

and what about on_command_error, just that one in your main script?

slate swan
#

oh i dont have it

#

i deleted it

hushed galleon
#

ah ok, so no others

slate swan
#

no others

hushed galleon
#

then its possible one of your on_message listeners is processing the commands twice

slate swan
#

oh wait i do

#

@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = "You have cooldown ! Please use this command again in {:.2f}s".format(error.retry_after)
await ctx.send(embed)
else:
raise error

hushed galleon
#

ah i thought you meant you had deleted that one

#

well either way 0 or 1 on_command_error is fine

slate swan
#

oh okay

hushed galleon
#

does any of your listeners have a await bot.process_commands(message)?

slate swan
hushed galleon
hushed galleon
#

if its not the same as the one shown in the file you pasted, then you had 2 on_command_errors

slate swan
#

like i had two

#

one for cooldown and one for unknown commands

hushed galleon
hushed galleon
#

agh its all conflicting

#

your previous screenshots would suggest two on_command_errors could have raised the same error, but the tracebacks would suggest your bot processed the same message twice

slate swan
#

how is that possible

#

how can i fix it now

hushed galleon
#

just to make sure, did you ctrl+f the phrase "process_commands"?

slate swan
#

no

hushed galleon
#

oh and what happens if you use a command like normal

slate swan
#

i did on_command_errors

hushed galleon
#

does the bot respond twice or just once

slate swan
#

but yeah w ctrl f

#

ill try

hushed galleon
#

ok that would definitely suggest the command was invoked twice

slate swan
#

i dont understand how

hushed galleon
#

any use of the word invoke in your code?

slate swan
#

No

hushed galleon
#

usually the library itself should never be processing a message twice, leaving the other cause to your code

slate swan
#

should i remove and install visual studio code again?

hushed galleon
#

to rule out nextcord, what happens if you create another script with commands.Bot and just one command? e.g. py bot = commands.Bot(...) @bot.command() async def test(ctx): await ctx.send('hello world!') bot.run(...)

slate swan
#

great idea tbh

#

i will try

hushed galleon
#

perhaps try changing the command_prefix as well, first with the same prefix and then something different

#

actually just seeing the bot respond to !test with a "command not found" for same prefix would mean there's a second instance of your bot

slate swan
#

that works

spring summit
#

does anyone know why this shit blocks every command

hushed galleon
# slate swan

without changing your prefix, does !test happen to do anything or nothing?

slate swan
#

ill try

hushed galleon
#

so,

  • no second instance, and
  • working test script, and
  • nextcord not broken
#

then its likely an issue with your first bot

slate swan
#

not w the cogs right?

hushed galleon
#

it might be

slate swan
#

ill check on the bot thank you!

hushed galleon
#

do you happen to have the source code hosted on github?

slate swan
#

No

hushed galleon
hushed galleon
slate swan
#

like in cogs its @commands.Cog.listener()

hushed galleon
slate swan
hushed galleon
#

yeah thats exactly the issue

#

listeners dont have to do process_commands

slate swan
#
    @commands.Cog.listener()
    async def on_message(self, msg):
        Channel = self.bot.get_channel(996119147337494538)
        if msg.author.bot:
            return
        embed = nextcord.Embed(title=f"New feedback!", description=f"__**User:**__ \n {msg.author.mention} \n \n __**Feedback:**__ \n{msg.content}", timestamp=datetime.now() , color=0x4e80cf)
        embed.set_thumbnail(url=msg.author.display_avatar.url)
        embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
        await self.bot.process_commands(msg)
        if msg.channel is not Channel:
            return
        moji=await Channel.send(embed=embed)
        await moji.add_reaction(':Fishy:')```
spring summit
cerulean folio
#

Hi guys, does bot.fetch_user() has problems with some ids?

hushed galleon
slate swan
#

like

#

i did, idk why i said bot.event

slate swan
#

@commands.Cog.listener()

slate swan
hushed galleon
#

mhm

slate swan
#

i removed ill check now

#

holding fingers

hushed galleon
slate swan
#

WORKS

#

U R A MAGICIAN

#

THANK YOU SO MUCH OMG

slate swan
#

🚶i almost never tried fetching a user

#

why do I keep getting restricted by cloud flare when my bot is sending messages to channels?

#

too many requests?

hushed galleon
slate swan
#

oh 😦

#

i dont have any other way to host

hushed galleon
#

ive heard you can write kill 1 in the shell as a temporary workaround, but replit's not exactly a good host for discord bots

slate swan
#

i have 8 times

#

idk replit use to be reliable

devout phoenix
#

can I handle events synchronously?

slate swan
#

now its not

hushed galleon
slate swan
#

yea there probaly gonna make it paid

#

😭

hushed galleon
#

i thought they already did with their hacker plan, whatever it was

slate swan
#

yh but you can host with uptimerobot for free

#

and they prob dont want that

hushed galleon
devout phoenix
#

I'm using discord.py and pyqt, having issues because the discord lib is async

hushed galleon
#

i believe you'd want to look into asyncio's bridge functions (wrong term?) for interoperability then

spring needle
#

Why it says local variable defined in enclosing scope on line xx referenced before assignment

#

I declared a variable outside the async def and try to use it inside an async def

#

More specifically, an int variable = 0 and I try to make it + 10 everytime the bot.command is run

hushed galleon
devout phoenix
#

I tried asyncio already, but I'm getting these errors

ValueError: a coroutine was expected, got <async_generator object Messageable.history at 0x7f33981df6c0>```
#

the code's just py print(asyncio.run(channel.history(limit=50)))

hushed galleon
#

asyncio.run isnt what you'd use for that

#

that has to create an entirely new event loop to run coroutines

devout phoenix
#

sure, but that's still a weird error in that case

hushed galleon
#

eh it makes sense

#

anyway you'd want a thread running the event loop for discord.py, separated from your main thread

devout phoenix
#

yeah but I'd have it on another thread again, would I not?

hushed galleon
#

and then use asyncio.run_coroutine_threadsafe(coro, loop) in your pyqt thread to execute async coroutines

#

the history() generator is a bit more complex though, you'd have to make a new async function just to flatten it into a list of messages

devout phoenix
#
TypeError: A coroutine object is required```
slate swan
#

history returns an async_iterator not a coro

devout phoenix
#

so the issue is that it's a generator?

#

I'll try with a regular one, hold on

hushed galleon
#

e.g. ```py
async def flatten(gen):
return [x async for x in gen]

in your pyqt thread:

future = asyncio.run_coroutine_threadsafe(
flatten(channel.history(...)),
loop
)
messages = future.result()```

devout phoenix
#

and I can use a callback instead of blocking, right?

hushed galleon
#

pyqt has their own threading stuff i believe

devout phoenix
hushed galleon
#

the whole library is designed with async/await

devout phoenix
#

anyways future.result() seems to block indefinitely

slate swan
#

anyone got a good free host for discord bots replit stinks (used to be gud)

hushed galleon
#

asyncio's a way to do concurrency in just one thread, quite performant for I/O-bound work

hushed galleon
devout phoenix
#

I'm really confused why this couldn't all run on a single thread

spring needle
#

How can I get how long until a member is unmuted

#

What I mean unmuted is the member has been timeout

hushed galleon
slate swan
unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None if the user is not timed out.

New in version 2.0.

spring needle
devout phoenix
spring needle
naive briar
#

timed_out_until

spring needle
#

Dam

#

Also another question, what if I just want to know how many seconds left until unmute

#

If I timeout 10 secs, after 5 secs there’s 5 secs left before unmute, and I want to let the bot know it’s 5 seconds left

naive briar
#

Use Discord's timestamp format

#

<t:1667921592:R>

spring needle
#

Let me search

nova mauve
#

Quick question, say I want to dm a user they’ve been muted, what if I wanted to delete that message after a certain amount of time, how would I go about that?

sick birch
#

!d discord.Member.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
sick birch
#

If you'll notice there's a delete_after kwargs

hushed galleon
#

if the mute is for a long period of time, you might have to store the channel+message id and timestamp in a database

nova mauve
hushed galleon
#

yea, then you can use Client.get_partial_messageable() + PartialMessageable.get_partial_message() + PartialMessage.delete() to remove it

nova mauve
hushed galleon
#

its new in dpy 2.0

#

PartialMessage[able]s are just there if you want to make particular API requests (send/edit/delete) without having to fetch the actual channel/message objects

nova mauve
#

i barely use this module n whenever i do there’s always new shit added

nova mauve
slate swan
#

you can just use bot.http.delete_message(/s)

versed comet
#

can someone please help me? it's giving error in dotenv, I think I uninstalled it by accident

#

the bot is not initializing

#

plsss

slate swan
#

how can I # the channel?

#
 @discord.ui.button(label='Open Ticket', style=discord.ButtonStyle.green)
  async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
    with open('tickets.txt', 'r') as f:
        words = f.read()
        test = words.split()
    if str(interaction.user.id) in test:
      await interaction.response.send_message(f"{interaction.user.mention} you already have a ticket open. #ticket-{interaction.user.id}", ephemeral=True)
    else:
#

this is my code

mossy jacinth
#

can someone help me? why does it say 'User' object has no attribute 'edit'

winged linden
#

I'm trying to make a leaderboard command for my bot. I was hoping someone could assist me with this.

winged linden
mossy jacinth
slate swan
mossy jacinth
slate swan
#

yea but I need to get the channel id or the channel

#

and this is when they click open ticket

winged linden
#
f"<#{interaction.channel.id}>"
slate swan
slate swan
#

how do I get the channel id....

winged linden
slate swan
#

that will return the support channel

winged linden
#

You want it to return their ticket?

#

You need to store who owns each ticket somewhere

slate swan
#

Store the ticket channel ID in your database whenever someone makes a new ticket then

winged linden
#

^

#

Store their user id aswell in the same record

#

And make it remove the record once the ticket is closed

slate swan
#

i have the user id stored

winged linden
#

In your database?

slate swan
#

everytime a user makes a ticket there id gets stored

#

if its in there they cant make another

dull terrace
#

in a text file?

slate swan
#

with open('tickets.txt', 'r') as f:
words = f.read()
test = words.split()
if str(interaction.user.id) in test:

winged linden
#

you would have to store the channel along with the userID

slate swan
#

Then store the ticket ID with the user ID so they are associated with one another

#

wait what

slate swan
#

can you help me on this

winged linden
#

Basically right now your just storing their user id when they make a ticket

#

but that user ID isn't associated with any channel or anything

#

So you can't grab the ticket

slate swan
#
channelid = await c.send(f"{interaction.user.mention} Please wait for staff. ({client.ticket}), to close this ticket do .close. Your next ticket can be open in 5m.")
int(channelid)
#

would this work?

#

to get the channel id

winged linden
#

no?

dull terrace
slate swan
#
def save_warn(ctx, member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] += 1

    with open('warns.json', 'w') as f:
         json.dump(warns, f)

def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] -= amount

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
#

could I use this warn code?

winged linden
#

you can use aspects of it

#

But if you mean copy and paste no

dull terrace
#

do you understand what dictionaries are and how to use them?

slate swan
#

I tried to use a .json like 2 years ago when I was new to dpy to store prefixes and stuff

#

databases are way better, I was noob back then

dull terrace
slate swan
#

i just need help storing it

#

and reading it

cloud dawn
slate swan
slate swan
spring needle
#

If I want to make a function that timeout user for 10 secs every time the command is-used, how can I make the timeout accumulable?

primal token
sick birch
#

meanie i cry

slate swan
spring needle
#

Yes

cloud dawn
#

New flag for robin spammer as well.

slate swan
# spring needle Yes

That seems like a weird way to handle a timeout command.
But Member.timeout accepts datetime.datetime as the date/time at which the user will be un-timed-out. So you can probably store that somewhere and use it to figure out how much longer to keep a user timed out for, if they receive another time-out whilst already being timed out. But I don't know exactly how you'd go about doing it.

slate swan
cloud dawn
#

It's actually better to use timedelta rather than datetime objects considering time zones.

slate swan
#

True true
Again I've never really used timeout so I don't know the best way to go about doing this sort of stuff

cloud dawn
#

I've made a command if you're interested.

slate swan
#

It's fine :) someday I'll stop procrastinating and learn everything properly, but thanks lol

cloud dawn
#

I meant just as example.

slate swan
#

if you wanna show me then sure

spring summit
#

i get no errors, but the the command doesnt work

slate swan
#

@spring summit maybe do keyy_codes.read()

#

Very nice!

cloud dawn
#

I don't think you can overengineer it much more lol

slate swan
#

I have the tall task of trying to build a multi-player poker game in my bot. Might ditch the multi-player aspect and just do player-vs-dealer.

#

bro I want to make a game in my bot

#

pls help me 😭

cloud dawn
granite plume
#

how do you update an embed

slate swan
#

embedname.edit(embed=newembed)

cloud dawn
#

Just edit the message.

granite plume
#

alright thanks

#

is embed.edit a real thing?

cloud dawn
#

Unless you name the message that way I guess.

granite plume
#

then how do you edit the message

cloud dawn
granite plume
#

message.edit?

spring summit
cloud dawn
slate swan
#

@spring summit show code

slate swan
# cloud dawn Interesting, tough with poker night it's a tough beat.

Evaluating the different cards and searching for pairs, full houses, etc is gonna be the main complication for me 😭 I have a vague idea of how to implement everything but hopefully once I get it all done I can start looking at releasing the first official version of the bot :-).

cloud dawn
slate swan
#
with open('file.txt', 'r') as f:
        read = keyy_codes.read()
        read = read.split()
        if str(ctx.author.id) in read:
#

try to do this

spring summit
slate swan
#

alr

cloud dawn
#

If you'd represent card to values 1 to 14

slate swan
# cloud dawn Well... to be honest they are just values and combo's.

I can get confusing quickly though
If 2 players both get 1 pair you then gotta look at the value of the pairs
Then if they both get a pair of 9s you have to go to the highest suit
Idk lot's of tiny details to account for, then again that's coding for you
Maybe I'm just small-brain when it comes to python

#

whats the best way to make a game in py? like a chicken fight game

#

how can I make ppl join and fight?

cloud dawn
slate swan
#

That's exactly the type of system I am already using in other games such as Blackjack. I can re-use parts of that code.

#

Though blackjack is much simpler since suits don't play any role.

#

Is it possible to add buttons to webhooks?

#

Anyway I gotta go cook cya guys round

granite plume
#

this would be easier to explain if i had the code

#

but i don't have a variable called "message"

#

just ctx and embed

cloud dawn
#

Show what you got so far.

granite plume
cloud dawn
#

I'd rather not or is private code?

granite plume
#

i'll just show you here it's a US/canada capital game bot

#
                state = curstates[i]
                embed=discord.Embed(title=f"Round #{i+1}: What is the capital of `{state}`:",\
                                    description="Type `$guess` or `$g` before the capital to make a guess", color=0x4278f5)
                await ctx.send(embed=embed)
                
                #=await ctx.send(f"Round #{i+1}: What is the capital of {state} (Type `$guess` or `$g` to make a guess): ")
                user_guess = (await bot.wait_for('message', check=check)).content
                #Check to see whether user uses $guess or $g, or if the command is used at all in the first place
                while not user_guess.startswith('$g'):
                    user_guess = (await bot.wait_for('message', check=check)).content
                
                if user_guess.startswith('$guess'):
                    user_guess = (user_guess.removeprefix("$guess")).strip()
                else:
                    user_guess = (user_guess.removeprefix("$g")).strip()
                
                #THE MAIN THING ↓↓↓↓↓↓↓
                if state in territories:
                    cur_dict = territory_dict
                else:
                    cur_dict = main_dict
                if user_guess.capitalize() == cur_dict[state].capitalize():
                    embed=discord.Embed(title=f"Good job {ctx.author}! You are correct! :)",\
                                        description=f"State: `{state}`\nThe correct answer was: `{cur_dict[state]}`", color=0x0ca307) 

                    await ctx.send(embed=embed)
                    #=await ctx.send("Good job! You are correct! :)")
         
                else:
                    embed=discord.Embed(title=f"You're wrong {ctx.author} :(",\
                                        description=f"State: `{state}`\nThe correct answer was: `{cur_dict[state]}`", color=0xe34d2b) 
                    await ctx.send(embed=embed)
#

see how there are 2 embeds?

#

i want to edit the first embed to have the 2nd embeds content

cloud dawn
#

await ctx.send(embed=embed) return a message object

#

So msg = await ctx.send(embed=embed) is a valid syntax.

granite plume
#

instead of editing the embed

#

it just sends this

slate swan
#

🥶 long time no see this channel

granite plume
#

<Message id=(not sharing with this server) channel=<TextChannel id=(not sharing with this server) name='bot-testing' position=2 nsfw=False news=False category_id=(not sharing with this server)> type=<MessageType.default: 0> author=<Member id=(not sharing with this server) name='(not sharing with this server)' discriminator='(not sharing with this server)' bot=True nick=None guild=<Guild id=(not sharing with this server) name='(not sharing with this server)' shard_id=0 chunked=True member_count=6>> flags=<MessageFlags value=0>>

slate swan
#

looks like you're using jishaku

granite plume
#

what's that

slate swan
#

nvm

granite plume
#

i just wanted help editing an embed

slate swan
#

!d discord.Message.edit

unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
slate swan
#

🥶 yes

granite plume
#

that's what i did

slate swan
#

bruh?

#

can someone help w making an slash command into a task

slate swan
slate swan
#

may i have a look at ur code?

slate swan
# slate swan eh, mind elaborating it a bit?

"that's because its running it all in the single /create command... the 2 slash commands aren't directly connected by anything...
I suggest using nextcord tasks for this instead..." someone told me that

granite plume
# slate swan bruh?

basically

embed=discord.Embed(title=f"Round #{i+1}: What is the capital of `{state}`:",description="Type `$guess` or `$g` before the capital to make a guess", color=0x4278f5)
bot_response = await ctx.send(embed=embed)

embed=discord.Embed(title=f"Good job {ctx.author}! You are correct! :)",\
                    description=f"State: `{state}`\nThe correct answer was: `{cur_dict[state]}`", color=0x0ca307) 
bot_response.edit(embed=embed)
await ctx.send(bot_response)
#

that didn't work at all

slate swan
#

so

#
await bot_response.edit(embed=embed)
granite plume
#

o h

slate swan
#

try it & lemme know if u still face issue 🥶

granite plume
#

ok

slate swan
#

would be nice if u tell me the same thing that u told that 'someone'

granite plume
#

alright it works

#

thanks @slate swan

slate swan
#

gg bro

slate swan
slate swan
#

how about u create a giveaway, & the giveaway will have an ID. and in order to end any giveaway one has to pass that ID, given that it has to be used by someone who has perms & is in the same server

#

🥶 lmk if u find it hard to understand or if u ain't getting my point

slate swan
#

yes

#

how do i make an id to a giveaway that wasnt created yet

slate swan
#

well, just have 2 attribtues in the table

#

does is have documents?

#

one will have the message ID of the giveaway message & 2nd will be the giveaway ID

#

so u can store or change or add giveaway ID & stuff on your own

#

thank u sm!

slate swan
slate swan
indigo pilot
#

Does anyone know if theres a way to access all questions, or answers in one var for the model form?

slate swan
#

hm

#

how many questions you're expecting to be there?

indigo pilot
#

im doing one form that will display questions depending on a global var value, but after i display them i set it back to none so it dosnt show the wrong questions to someone else

#

but since i set it back to none i wont know what questions there are

#

i do use a format just Question(number)

#

but there will be a diff amount of questions for diff values

indigo pilot
slate swan
#

hm

indigo pilot
#

havnt filled everything in yet but thats what i mean

#

i cant just check if self.question{number}.value all the way up to 6 because question{number} will litterly be none if it isnt a question so

slate swan
#

thats not how you use classes

indigo pilot
slate swan
indigo pilot
#

and thats how ive used forms ever since they came out and there isnt any problem

indigo pilot
#

not the best way i would like to do it

#

but its the only way i could think of

cerulean folio
#

Hi guys !
I just coded this command that will create a Quiz. The quiz has two main functions one for asking the questionnaire and one for cancelling the questionnaire if someone writes 'cancel'.
Although this is the output I'm getting when testing it (Question 1 has been validated by question 2 before the quizz gets stopped by the cancel. I'd want it to cancel instantly):
https://paste.pythondiscord.com/pibomexeqi

EDIT: Also Question 1 shouldn't have trigger question 2 when I wrote 'cancel' :o

slate swan
#

you're aware that you can use the init right?

indigo pilot
#

theres one more way i think but its alot more work

indigo pilot
silent portal
#

Hey, I'm making a Voice XP System and don't know what is more efficient. Should I create a asyncio.sleep() for every user joining a VC? Or save the Datetime of the Join in a DB and go through it with a for loop?

slate swan
#

the latter

slate swan
cerulean folio
silent portal
slate swan
indigo pilot
#

i just re-read this, and this would work out

My problem now then would be, each department has diff amount of questions, some could have 2 others 6, so i woul dneed a way to still make the amount of questions that i need

#

Unless i can make 6 questions, then remove the ones i dont need inside the innit but i dont think that will work ?

unless setting it none would work

silent portal
abstract kindle
#

@slate swan, could I setup an error handler to try and catch the errors manually?

#

I'm still having the issues where I don't get any errors

rustic edge
#

Every time I run the command $bread, I get the error "discord.ext.commands.errors.CommandNotFound: Command "bread" is not found"

My code:

import discord
from discord.ext.commands import Bot
from discord import Intents
intents = Intents.all()
client = Bot(intents=discord.Intents.all(), command_prefix='$') 

@client.event
async def on_ready():
    print(f'Bot connected as {client.user}')
    
@client.command
async def on_message(message):
    if message.content == 'bread':
        await message.channel.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')

        
client.run("token")

abstract kindle
indigo pilot
#

i dont use non slash cmds but im pretty pos bc your using a event not a command lol

silent portal
slate swan
abstract kindle
#

I forgot the parenthesis after the decorator, don't forget those

rustic edge
#

Whats does CTX stand for?

abstract kindle
#

And I had ctx.channel lol just go with beros

#

ctx stands for context, which is basically just the context of the command being used. For example, who used it, where it was used

abstract kindle
indigo pilot
#

yall type so fast jeez 😭

#

snet your message before i could even start typing

abstract kindle
#

Comes from years of LoL @indigo pilot

#

Gotta flame with speed and eloquence

indigo pilot
#

Lmaoo

slate swan
#

im high yeah

hushed galleon
waxen cradle
#

why content.startswith() doesn't work? if i delete it the bot will respond to any message sent but i want to make a special command for it

abstract kindle
abstract kindle
naive briar
abstract kindle
#

Scroll up and look at WhineyMonkey's question

indigo pilot
naive briar
waxen cradle
slate swan
waxen cradle
naive briar
#

default does not have message_content by default

abstract kindle
#

@slate swan can you see if I link a private repo?

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

naive briar
#

Intents.default have all intents but privileged ones

abstract kindle
#

@waxen cradle

@client.command()
async def hello(ctx):
  await ctx.send("Hello!!")
```This is an example of a command
slate swan
abstract kindle
#

I see. I think I'll try to setup another bot on another computer and try to reproduce it first

rustic edge
abstract kindle
#

Sorry!!! send error @rustic edge

indigo pilot
rustic edge
#

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


import discord
from discord.ext.commands import Bot
from discord import Intents
intents = Intents.all()
client = Bot(intents=discord.Intents.all(), command_prefix='!') 

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

@client.command()
async def bread(ctx):
    await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')
async def cat(ctx):
    from IPython.display import Image
    import requests, json 

    catURL = 'http://aws.random.cat/meow'

    imageURL = json.loads(requests.get(catURL).content)["file"]

    img = Image(requests.get(imageURL).content)
    await ctx.send(img)
        
client.run("token")```
silent portal
#

Why are you importing stuff in ur command?

rustic edge
#

im so dumb

#

ty guys ❤️

slate swan
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

abstract kindle
#
from IPython.display import Image
import requests, json 


@client.command()
async def bread(ctx):
    await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')

@client.command()
async def cat(ctx):
    catURL = 'http://aws.random.cat/meow'

    imageURL = json.loads(requests.get(catURL).content)["file"]

    img = Image(requests.get(imageURL).content)
    await ctx.send(img)
silent portal
#
import discord
from discord.ext.commands import Bot
from discord import Intents
from IPython.display import Image
import requests, json 

intents = Intents.all()
client = Bot(intents=discord.Intents.all(), command_prefix='!') 

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

@client.command()
async def bread(ctx):
    await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')

@client.command()
async def cat(ctx):
    catURL = 'http://aws.random.cat/meow'

    imageURL = json.loads(requests.get(catURL).content)["file"]

    img = Image(requests.get(imageURL).content)
    await ctx.send(img)
        
client.run("token")```
rustic edge
#

ty

silent portal
#

yw

slate swan
#

❎ ```py
imageURL = json.loads(requests.get(catURL).content)["file"]

✅ ```py
    imageURL = requests.get(carURL).json()["file"]
hushed galleon
indigo pilot
hushed galleon
#

i think your questionnaire can be done just with buttons/modals/app commands (for the attachment part), but it would be much more complicated than a message-based implementation

upper pelican
#
async def main(ctx):
    while True:
        if console.alive:
            frametime = time.time()
            bot.run(frametime)
            scheduler.run(frametime)
            console.run()
            await client.send()
            await asyncio.sleep(0.5)
        else:
            await client.close()
            print("QUIT NOW.")
            os._exit(0)
            

client.c.loop.create_task(main())
client.run()

AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook i dont understand what should i do exactly

indigo pilot
#

and just make people use imgur or something

#

or did i missunderstnad you

#

because if i can do it like that, my life is so easy

hushed galleon
#

pretty much

slate swan
#

is varthing a classvar?

indigo pilot
# hushed galleon pretty much

i woul dlove to cry rn

wish i knew that 2 months ago, the amount of pain and suffering ive done with forms to do dymanic questions with jaggy ways

#

😭
but thank you

#

then i guess i can just access my self.varthing or what ever again in the code to check what set of questions its using

indigo pilot
#

its nothing rn i just was sharing a example

slate swan
#

passed into the model as in inside the init right?you can access it from there directly

dense coral
#

Who needs help?

indigo pilot
#

im not needs help

primal token
#

i do

indigo pilot
#

i just didnt know i could use self.add_item or what ever inside innit to define questions

dense coral
#

just a second

upper pelican
#

alr

dense coral
#

why you are use on this ? await asyncio.sleep(0.5)

#

but, I think that this is not the problem

upper pelican
waxen cradle
#

Guys, if i want my bot to send a message everyday at a specific hour only how can i approach this (i tried with the good old While True and time.sleep() and asyncio.sleep, but they dont work)

dense coral
#
async def watching():
  await bot.wait_until_ready()
client.loop.create_task(watching())```
This is the template for the loop
waxen cradle
#

that was fast

#

thanks tho🙇‍♂️

upper pelican
waxen cradle
slate swan
silent portal
#

Which one's better for efficiency?

timer = threading.Timer(30, do_something)`
timer.start()```
or 
```py
asyncio.sleep(30)
slate swan
#

2nd

abstract kindle
#

how do I make an app command error handler

slate swan
#

on_app_command_error event

#

waittt i think there's one more thing that can cause your no error issue, do you use bot.run() or bot.start() ? @abstract kindle

abstract kindle
#
async with bot:
    await load_extensions()
    await bot.start(data["token"])
#

then ```py
ayncio.run(main())

slate swan
#

yeah thats the issue, you'll have to manually configure logging if you use bot.start, can you just try replacing it with bot.run() for a while and try?

abstract kindle
#

bot.run is not a coroutine, right

slate swan
#

yea you wont be awaiting it

abstract kindle
#

[2022-11-08 14:17:17] [INFO ] discord.client: logging in using static token

slate swan
#

yeah great, it didnt use to print earlier right?

abstract kindle
#

I think it fixed the logging? But how come it says logging in with a static token? Also none of my commands are being found

slate swan
#

static token means a bot token, thats totally normal

abstract kindle
#

None of the commands are being found anymore. Also, how come I would remove load_extensions()? That loads all my cogs

slate swan
#

can i see your updated bot running code

abstract kindle
#

Hold on, I have everything in my main file in a main() function so I could use await, is that fine?

slate swan
#

ofcourse

abstract kindle
#

I think I did that so I could start tasks in the on_ready() event

slate swan
#

you could start them in a setup_hook

#

unless you use a fork

abstract kindle
#

I had a setup_hook, but that was so I could setup bot.db for my database

#
bot.run(data["token"])
asyncio.run(main())
#

This is the part that runs though

slate swan
#

just move the bot.run() inside your main function bud

#

your bot.run() is blocking asyncio.run() here, so no extensions are getting loaded

abstract kindle
#

but not under

await with bot:
slate swan
abstract kindle
#

okay that's what I had, one sec

#

yeah i got this error

RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
slate swan
#

!d discord.utils.setup_logging

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig "(in Python v3.11)") but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") to set up logging if `log_handler` is not `None`.

New in version 2.0.
abstract kindle
#
@bot.event
async def on_ready():
    print("Bot is ready.")
    activity = discord.Game("-help")
    await bot.change_presence(status=discord.Status.online, activity=activity)
    
    print(f"-- BOT RAN --\nRan at: {now}")
    drop_task.start()
    farm_task.start()

I do have this IN the main function

slate swan
#

that should create an issue

abstract kindle
#

Got it. Move it outside the main?

slate swan
#

oops, * not create an issue

abstract kindle
#
async def main():
    async def load_extensions():  # Function for loading cogs upon bot.run
        for filename in os.listdir('./Cogs'):
            if filename.endswith('.py'):
                await bot.load_extension(f'Cogs.{filename[:-3]}')

    async with bot:
        await load_extensions()
        bot.run(data["token"])
``` This is entire main function now
slate swan
#

actually you know you can fix it even more easily

#

just revert the code to how it was

#

and add discord.utils.setup_logging() just before bot.start

#

it will fix your issue

abstract kindle
#

Life saver

#

Actually. This was so frustrating!!!!

#

Thanks a ton !!

slate swan
#

it took a whole day lol

abstract kindle
#

Yeah I was so lost

slate swan
abstract kindle
#

I was just putting print statements and debugging ALL over the place and it was getting old

abstract kindle
#
[2022-11-08 14:34:07] [INFO    ] discord.client: logging in using static token
[2022-11-08 14:34:09] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 261225937d7fda3da5ff7552e1262164).
```So this is normal?
#

It scares me cause red = bad

slate swan
#

yes thats totally normal

#

INFO logs are just about the actions your lib is doing
you just gotta check warning logs if any of them get raised

abstract kindle
#

Got it

#

Also, I'm kinda new to slash commands. What's the best practice for syncing commands?

slate swan
#

i use stuff similar to setup_hook for automatic syncing
people will also suggest to use a command to do the syncing

#

so the code doesnt sync itself all the time

#

can i use database in cogs?

abstract kindle
#

yeah, previously I made a reload command to reload whatever Cog I chose, and I had an option to sync commands

slate swan
#

oh thats great

#

thankss

slate swan
abstract kindle
#

cool. also, I run my bot in 2 different servers. Would I have to have 2 different sync lines?

slate swan
#

idk about syncing stuff in discord.py, you can wait for someone else to respond maybe
( if its a global command you wont have to sync seperately lol )

abstract kindle
slate swan
#

yea the applicationcommands scope

abstract kindle
#

does the decorator also work? as in

@app_commands.guilds(856915776345866240, 977351545966432306)
slate swan
#

i think it should

#

!d discord.app_commands.guilds

unkempt canyonBOT
#

@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.

When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.

Note

Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.

Example...
slate swan
#

yea

#

nextcord.errors.ApplicationInvokeError: Command raised an exception: OperationalError: no such column: command

abstract kindle
#

perfect. Thanks again for your help sarth, saved me a lot of frustration

slate swan
#

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

slate swan
potent spear
potent spear
#

you can put that db stuff in your bot file btw
add a db connection as a botvar

waxen cradle
#

why doenst content.startwith(!) work inside the command?

potent spear
#

also, time.sleep is blocking, you should use await asyncio.sleep(...) from the asyncio lib

waxen cradle
waxen cradle
potent spear
silent portal
#

How can I make the @tasks.loop(minutes=2) start after 2 Minutes and not run once and repeat every 2 mins? So the first run starts after 2 mins

slate swan
idle laurel
#

what are the limitations with background tasks in discord?

slate swan
#

what exactly do u mean by that

slate swan
slate swan
idle laurel
#

i want to creat a mongodb streamer which will send a user a message in the background when some values change

#

originally i was going to make this run seperate to the bot but i dont think i can send private messages without running it in in discord.py/ nextcord?

silent portal
#

Also are normal commands (not slash) now deactivated completely for public bots?

winged coral
#

Nope, unverified bots still get content intent without filling out the application

idle laurel
#

is there a way can send direct messages without using discord.py thought the bot?

slate swan
#

yeah use the rest api

idle laurel
#

i need the users channel id for this tho? not just the user id?

slate swan
#

you send the message to their dm channel, not the user object

#

their user-id is the channel-id there

idle laurel
#

https://discord.com/api/v9/channels/user-id/messages returns me a 401 error, when using the bots authorization code

slate swan
#

show ur code lol

idle laurel
#

im just using postman atm for that, not wrote anything up

#

when browsing through the requests ive sent when sending a message the channel-id isnt the same as user-id for private messages?

slate swan
#

it includes the "@me" yeah

#

wait ill verify and ping

idle laurel
#

alright

slate swan
# idle laurel alright

okay so you gotta create a dm channel and get it's ID first then you can send a message there

#

also while using postman, did you provide the headers?

idle laurel
#

so ive just tried that changing the auth token and recipients and 401 error again -.-

slate swan
#

401 means lack of authorization

idle laurel
#

using the bots token

slate swan
#

did your headers look like this ```py
{"Authorization": "Bot <your token here>",
"Content-Type" : "application/json"}

idle laurel
#

ive got these enabled with the correct token, still coming back 401. ill try without postman see if thats the issue

slate swan
#

your authorization field is wrong

#

it should be "Bot ...", not just "..."

idle laurel
#

oooh, mb

#

smh that worked fine lol

#

cheers

spring summit
sick birch
# spring summit ?

You're sure this is where the error is? I don't see await channel.send('hello') in that image

spring summit
sick birch
#

And is it still the same error?

spring summit
slate swan
#

how would i wait for a specific users, user input
like if i were to do $input
and someone else says something for some reason it takes that instead

patent wagon
#

how do i make my discord bot leave the guild

primal token
#

!d discord.Guild.leave

unkempt canyonBOT
#

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

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
patent wagon
#

the last guild it was added to to be specific

primal token
#

You can always have a global var of the last guild it joined to or you can get the object

slate swan
patent wagon
slate swan
#

if ur using on_guild_join just do guild.leave() and it will leave the second it joins a guild

patent wagon
#

ok but

#

thats only if its len(client.guilds)>1

#

maybe i want len(client.guilds)> some N

slate swan
#

no client.guilds does not put the guilds in any order

#

so wouldn't work

patent wagon
#

what the

#

bruhhh

slate swan
#

u would just be leaving random guilds at that point

patent wagon
#

i can append guild ids in a list

#

and leave the one with the L[lenL-1]

#

could i?

slate swan
#

no. all that would do is leave the last guild u appended

#

u cant get the last guild ur bot joined other than getting the guilds id and getting the guild obj

patent wagon
#

why does it say leave isnt defined

primal token
#

Because its a method and isnt in scope

patent wagon
#

wdym?

patent wagon
primal token
#

You use the method on a guild object?

patent wagon
#

like this?

primal token
#

Guild.id returns a snowflake and gets treated as an int, no? So using int.leave which isnt a method the object has if not defined, isnt correct.

primal token
patent wagon
#

can u write the expamle

#

like is it just guild.leave()

spring summit
patent wagon
#

tysm

#

it worked c:

spring summit
indigo pilot
#

[2022-11-08 19:14:19] [ERROR   ] discord.ui.view: Ignoring exception in view <Commissions_Question01_Department timeout=None children=1> for item <Select placeholder='Select a department.' min_values=1 max_values=1 options=[<SelectOption label='Development' value='COM_DEP_1' description='MC Plugins, Discord Bots, Web Development' emoji=<PartialEmoji animated=False name='⚙️' id=None> default=False>, <SelectOption label='Minecraft Building' value='COM_DEP_2' description='Builder' emoji=<PartialEmoji animated=False name='🏦' id=None> default=False>, <SelectOption label='Design' value='COM_DEP_3' description='GFX, Web Design, Illustration, Vector Artist, 3D Artist, MC Texture Pack Designer' emoji=<PartialEmoji animated=False name='🎨' id=None> default=False>, <SelectOption label='Writing' value='COM_DEP_4' description='Writer' emoji=<PartialEmoji animated=False name='📃' id=None> default=False>, <SelectOption label='Video & Audio' value='COM_DEP_5' description='Voiceover, Video Editor, Trailers' emoji=<PartialEmoji animated=False name='🎙️' id=None> default=False>, <SelectOption label='Setups' value='COM_DEP_6' description='Setup Specialist, Server Administrator, Discord Setup Specialist' emoji=<PartialEmoji animated=False name='🪚' id=None> default=False>, <SelectOption label='Close' value='COM_DEP_CLOSE' description='Close your ticket.' emoji=<PartialEmoji animated=False name='❌' id=None> default=False>] disabled=False>
Traceback (most recent call last):
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\kaelm\PycharmProjects\Main-bot-recreation\cogs\ticket\master.py", line 210, in select
    if option.value == "COM_DEP_1":
AttributeError: 'Select' object has no attribute 'value'```
https://i.leaked-your.info/dhZV99Nj
#

what is it again

#

i forget

#

i thought it was values[0] but that dosnt work so

sick birch
#

it's values not value

indigo pilot
#

pycharm is being homosexual then, said value was right but not values lul

#

thanks

#

one more question

#

is there something to mark a interaction as responded too?

#

so it dosnt say interaction failed

sick birch
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...
indigo pilot
#

just realised that haha

#

sorry

hushed galleon
#

you use the value attribute of the text input

indigo pilot
#

wdym?

hushed galleon
#

!d discord.ui.TextInput.value

unkempt canyonBOT
hushed galleon
#

i.e. py class MyModal(discord.ui.Modal): my_input = discord.ui.TextInput(...) async def on_submit(self, interaction): answer = self.my_input.value

hushed galleon
#

you have to store the text input somewhere

#

put it in a list or a dictionary or something

indigo pilot
#

mm

indigo pilot
#

how would putting them in a list or dict do anything

#

or

hushed galleon
#

so you're able to get the answers to each input

indigo pilot
#

how do i store them tho? since im using self.additem

#

questionone = self.add_item()
?

hushed galleon
#

construct the text inputs beforehand, then use add_item() afterwards

#

e.g. ```py
self.inputs = [
discord.ui.TextInput(...),
...
]
for text_input in self.inputs:
self.add_item(text_input)

and in on_submit():

answers: list[str] = [text_input.value for text_input in self.inputs]```

indigo pilot
hushed galleon
#

yes

indigo pilot
#

oo oke! thanks

then to access it, answers[0].value im guessing?..

hushed galleon
#

er no, the answers was showing how you'd turn that list of text inputs into a list of strings

#

if you dont care about that you can write self.inputs[0].value

indigo pilot
#

ahh oke

slate swan
#

is there any way to run a command when my bot goes offline?

sonic plover
#

hello! i'm trying to set up a bot but i can't install discord.py using pip. Anyone having the same issue?

ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects

#

idk if it's something really simple or a huge problem, because i started coding in python and in general recently, so i still don't know a lot. i'm working on the bot as a way to learn the language

slate swan
#

does anyone know how to fix this?

full ether
#

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

slate swan
#

thank you

versed comet
#

help me pls

#

Please, can someone help me? i'm trying to initialize my python bot and it's giving this error, it didn't give this error before

#

it's giving this error when booting

#

in that folder

slate swan
#

How do I do this

#

aint no way

slate swan
#

you type the answer to the questions dawg

#

WHAT DOCS 😭

#

fill out the info

slate swan
hushed galleon
#

you can either downgrade to 3.10 (the simple choice), or download the necessary build tools for pip to manually compile those wheels, which is sort of explained somewhere above your error message

hushed galleon
slate swan
#

I believe discord.py does not support this correct?

hushed galleon
#

discord.py supports all forms of interactions* in the latest release, 2.0
*barring the bleeding edge stuff, in particular role/user/mentionable select menus

slate swan
#

what do you mean by "*barring the bleeding edge stuff"

hushed galleon
#

as in the particular feature i described came out very recently (about one month ago), and 2.0 came out before then

#

its just a sidenote, modals are supported

hushed galleon
# versed comet

it seems there's something wrong with your dotenv package, perhaps related to a package conflict, though i dont understand why a package-lock.json file for npm is there
id ask about it in a help channel and also paste the output of pip list in your terminal (#❓|how-to-get-help)

slate swan
#

who wants to make a bot with me?

sick birch
#

i think we were discussing this a few days ago

#

not sure if that was you but someone sent an image of a select menu with roles and users

hushed galleon
#

yup that was me

sick birch
#

ahaha my bad, my memory is not all that great

hushed galleon
#

i think its out on master branch tho

shrewd apex
#

previously select menus were not visible on mobile client does it work now?

hushed galleon
shrewd apex
hushed galleon
#

ah i think i remember that too, it was a weird experience

#

the api straight up blocks selects in modals now (i tested it a minute ago)

shrewd apex
#

ic thanks for the info❤️

ionic garden
#

how would i have an argument

#

be a list of users

shrewd apex
#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
ionic garden
#

wb slash commands

ionic garden
#

ok yeah it works the same for slash command

glossy shore
#

Hello, I'm looking for ways to make my own discord.py custom events

@bot.event
async def on_my_event(param1,param2,*etc):
  pass

I came across this stack overflow post
https://stackoverflow.com/questions/64810905/how-do-i-emit-custom-discord-py-events

#

can any one please explain how Bot.dispatch works ?

#

I don't see it in the docs for discord.py

torn sail
unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

torn sail
#

Oh oops

torn sail
#

The event name should not have on_

glossy shore
#

is it async ?

torn sail
#

Nope

ionic garden
#

so apparently discord has select menus and stuff

#

where you can choose multiple
how would i do this? the closest is discord.ui.Select, and it doesn't exactly offer multiple select choices

glossy shore
#

@torn sail
just curious
what library does discord.py use to handle event-dispatching ?,

slate swan
#

How so u do that

naive briar
#

!d discord.ui.Select - Set the max_values to more than 1

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
slate swan
#

Thankss

golden hinge
#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
golden hinge
#

Hello, I'm looking to create a command to display the time dynamically based on the customer's location, normally it's possible but I don't know how to go about it 😅

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
upbeat gust
#

this can help do it for you

slate swan
#
{'cogs.modmail': ExtensionFailed("Extension 'cogs.modmail' raised an error: ModuleNotFoundError: No module named 'configuration'")}
Loaded: cogs.modmail
#
import discord
from discord.ext import commands

from configurations.configuration import config
from configurations.messages import res_msg
from utilities.functions import get_embed, confirmation
#

Why?

golden hinge
slate swan
#

if I’m not mistaking just doing using datetime.datetime.utcnow() will display the time based on their time zone.

placid skiff
#

nope, this will return the time based on the local machine, aka the current time where the bot or the program is executed

slate swan
#

that's now, not utcnow

#

!d datetime.datetime.utcnow it returns the utc time

unkempt canyonBOT
#

classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.

This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now").

Warning

Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
slate swan
#

shoulda specified, if u do it in the time stamp of an embed it’ll show correct time for that used

slate swan
vestal pine
#

hello so I am running a discord bot and hosting it over replit with an hosting file or actually keep_alive but I am having the problem in the image down there that its giving me the wrong time. I hope someone had this before and can help me with it

#

this error is also causing the bot not to get online

loud junco
#

Should I use image as the Monopoly board like myuu

loud junco
#

This thing means ur uptimerobot is working :/

vestal pine
#

yes, but the time is wrong

loud junco
#

Check ur token maybe?

vestal pine
#

I reseted and tried it