#discord-bots

1 messages · Page 169 of 1

silver reef
#

here is the code btw :

file = discord.File(r"C:\Users\userUwU\Desktop\test\Crypt Creeper.png", filename="image.png")
    
    embed.set_image(url="attachment://image.png")
    await ctx.send(file=file, embed=embed)


slate swan
#

more quality is not more delay

shrewd fjord
#

But sending an edited image shouldn't give delay

#

Saving image takes time but not sending

silver reef
#

3s

slate swan
#

because if its slow to just respond

silver reef
#

i changed the image

#

this one

#

and there was no delay

shrewd fjord
#

No need to use another method separate

silver reef
#

so i was thinking it just the quality

shrewd fjord
#

Nope...

silver reef
#

the elements of image u know

slate swan
#

prob ur internet tbh

silver reef
#

i literally did two images the same format same size but the delay time is different

silver reef
shrewd fjord
#

Editing image in good quality on code it takes time to save but while sending saved image through discord , there is no way it takes delay

shrewd fjord
slate swan
#

ur still uploading a high quality img lol

#

its ur internet making it slow

shrewd fjord
#

But still np

#

Yea processing can take time tho 💀💀

slate swan
#

especially if u just using a saved img from a directory

silver reef
#

last try

slate swan
#

that is even worse lmfao

shrewd fjord
#

Ye

silver reef
#

better than my wifi

shrewd fjord
#

That's true too 🗿

silver reef
#

just wanna check , not like iam gonna host my bot on replit 24/7

shrewd fjord
#

ahh like

#

async def method(url):
async with .......as session:
response = ........get(url)

#

Kinda like dat

#

It's separate method

slate swan
#

hey I need help I'm trying to make it where once you do *end and the paragraph of your advertisement but it does not work once it logged plz help

#

thats normal

vale wing
#

Man's trying to earn from discord bots

#

Imagine if I would do that stuff

#

Anyway what the problem is there

slate swan
#

how could I make it so that after running a certain command and the user types chunks of text how can I make it where the bot logs the chunks of text that the user writes? this is my problem and I tried doing that

slate swan
vale wing
#

😏

#

Actually we could probably integrate purchases to bobux after we make site just to try

#

Maybe will be enough to cover VPS costs

slate swan
vale wing
#

🧐

#

Ah got what you mean

#

One sec lemme give me docs link

slate swan
#

I did this by my self

shrewd fjord
#

Scam hm

vale wing
vale wing
#

BadModal for card info

shrewd fjord
#

Scem

shrewd fjord
exotic maple
#

idk if i explained that well

vale wing
#

Bobux bot codebase names be like
utils.utils.check_if_stupid
utils.views.BadModal
res/user_insults.json

vale wing
#

So why even store that

exotic maple
#

not discord message id

vale wing
#

What are they trying to achieve? Application reviews or smth

exotic maple
#

think so

slate swan
vale wing
#

Just attach a persistent view with deny/approve buttons, you can access the message via message interaction

slate swan
vale wing
slate swan
#

I usually do prefix commands not slash commands

slate swan
exotic maple
#

sorry im kinda thick

vale wing
slate swan
vale wing
slate swan
#

*end (user's large writing)

vale wing
#

Cause thick is like uh fat?

slate swan
#

and the bot logs it from there

#

but the bot logs a little bit of the advertisement

timid spade
#

how can i get message id of the message the bot sent
like on using a command bot replied with a message, how can i get that messages id or that message itself

vale wing
slate swan
vale wing
#
async def func(ctx, *, large_text)```
slate swan
exotic maple
vale wing
#

Bro you were supposed to look at the example, not scroll or anything

vale wing
exotic maple
#

wait

vale wing
#

message.reference.resolved

timid spade
vale wing
#

Uh

#

!d discord.TextChannel.history still not sure what you need

unkempt canyonBOT
#

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

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

Examples

Usage...
timid spade
vale wing
#

O

#
message = await channel.send(...)
message.id  # <-- here```
timid spade
#

yes thanks

#

got it

shrewd fjord
#

🗿

timid spade
#

🗿

shrewd fjord
#

So exenifix i am getting my beta bobux's $$?

primal token
#

You shouldn't be making sessions on each call of the method, use a single session. Why are you converting self.user_id to a string in an f string?

light violet
#

.

primal token
#

what?

#

You're missing my point? You shouldnt be using requests either?

#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
primal token
#

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

primal token
#

it can be, but lets not talk about that

#

Its an esoteric way, you should just use create_task or use a classmethod, but to avoid any other issues i would recommend using the latter

upbeat otter
#

that's why it was italicized

oblique fern
#

Ping or message me if you would be able to test the multiplayer game i made in discord.py

serene pagoda
#

``Traceback (most recent call last):
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

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

Traceback (most recent call last):
File "C:\Users\Nick\PycharmProjects\dis bot\test bot.py", line 37, in <module>
client.run("TOKEN")
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 580, in login
data = await self.http.static_login(token)
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\http.py", line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000224C55315E0>
Traceback (most recent call last):
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed``

#

Why am I getting this error

#

I'm sure I have the right token

#

And the bot has admin perms

hushed galleon
serene pagoda
#

Yeah I even tried making a new bot and different code but says the same thing

hushed galleon
#

so that means you edited your traceback to hide the token, right?

#

did you copy it from the Bot page of your application in the dev portal site?

serene pagoda
#

Yeah

serene pagoda
feral frost
#

anyone knows how i can make a timeout error for slash commands ?

#

message

serene pagoda
#

@hushed galleon so what now

hushed galleon
#

i have no idea what your original question is

hushed galleon
serene pagoda
#

Yeah

#

Also it happened on its own , im using the same code that I used before while it was still working

slate swan
#

Hello I bought a VPS on racknerd someone knows and can help me in uploading my files?

#

I have a main.py, requirements.txt and a data_mysql.sql

hushed galleon
#

creating a single ClientSession outside of your update_values() isn't needed, its an optimization as noid described which helps when making lots of requests to the same servers
also i dont know what check method you're referring to, nor do i know the purpose of polling updated loot information in the first place

#

but why are you trying to poll this information? is it for real-time updates?

slate swan
#

ik file Zilla but idk where can I get my sttp

hushed galleon
#

ah whatever in that code you commented out the request, so what was wrong with it before?

slate swan
#

and also idk where upload them

hushed galleon
#

well they didnt say to stop making requests entirely, just store the session somewhere

hushed galleon
# hushed galleon well they didnt say to stop making requests entirely, just store the session som...

e.g. ```py
bot = commands.Bot(...)

async def main():
# Create a single session here
async with bot, aiohttp.ClientSession() as session:
bot.session = session
await bot.start(...)

class User:
def init(self, bot):
self.bot = bot

async def update_values(self):
    async with self.bot.session.get("api-link") as response:
        ...  # retrieve the values and do your calculations like before

users = [User(bot), ...]
asyncio.run(main())```

#

what? no, only the session is stored, you're still making a new request each time you update

hushed galleon
#

its just different variable names, do whatever you want with them

#

whatever users you have in your loot_table

#

well you need access to the session in your update_values() method somehow

#

you can pass just the session instead of the entire bot, or get hacky and reference the bot as a global variable

hushed galleon
#

well given that you're referencing client as a global variable already, you can just write client.session to access it

#

also worth noting that if you werent using a main() function before, you'll need to manually call discord.utils.setup_logging() since that's one of the things client.run() would have done

vale wing
#

Or even use workflow for automation

slate swan
vale wing
#

Just take latest version of ubuntu, doesn't really matter

#

I meant latest LTS which is 22.04.1 iirc

#

There were weird ssh bugs in 22.11 when I tried it last time, had to rollback

vale wing
slate swan
#

both

#

ik better file Zilla

vale wing
#

Knowing git is an important skill, I suggest looking up tutorials

slate swan
#

yes but its possible to upload with file Zilla right?

vale wing
#

Yeah

#

I would recommend termius app cause it has both sftp client and ssh + nicer interface than firezilla's

#

Have been using it since got my first VPS

slate swan
#

terminus app is for uploading files?

vale wing
slate swan
#

never used it

vale wing
slate swan
#

@slate swan what’re you trying to do?

#

trying to host my discord bot on racknerd

#

it's a vps

#

Aye, trying to get my bot to read a list from a json in the directory, but its saying it cant find it?

main.py

from discord.ext import commands
from TOKEN import token
import asyncio
import os
intents = Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='!',intents=intents)

@client.event
async def on_ready():
    print("RijalBot online")

async def load():
    for file in os.listdir('./commands'):
        if file.endswith('.py'):
            await client.load_extension(f'commands.{file[:-3]}')

async def main():
    await load()
    await client.start(token)

asyncio.run(main())```

**cmds.py** [cog/extension]
```import discord
from discord.ext import commands
import json

file = json.load(open('narrators.json'))
narrators = file.get('narrators')

class cmds(commands.Cog):
    def __init__(self, client):
        self.bot = client

    @commands.Cog.listener()
    async def on_ready(self):
        print("CMD Cog working")

  # RIJAL COMMANDS BEGIN HERE:

    @commands.command()
    async def rijal(self,ctx, message:str):
        if message in narrators:
            await ctx.send("e")




  # RIJAL COMMANDS END HERE

async def setup(client):
    await client.add_cog(cmds(client))```

heres my directory
vale wing
#

Almost

green schooner
#

Hey any idea how to create those "forms" looking window, documentation or how they are called?

vale wing
#

Except you better subclass Bot and set the session as its attribute

#

Cause you need to overwrite __init__, setup_hook and close methods

green schooner
vale wing
#

@oblique sorrel set the session attribute in __init__ and overwrite this

async def close(self):
    await self.session.close()
    await super().close()```
green schooner
#

Yeah right, I am coding a bot to run applications for a Minecraft event I host and thaught those could be cool to use

vale wing
#

It's named session why would it be request

#

In overwritten MyClient.close()

#

Unrelated

#

Is it still that ChatGPT thing

#

!d discord.Client.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
vale wing
#

Ok see in your subclass you add this to __init__ (doesn't matter where exactly in it at all)

self.session = aiohttp.ClientSession()```
Then you make a method for your subclass (cause it exists in superclass, it's called *overwrite*)
```py
async def close(self):
    await self.session.close()
    await super().close()```

Running would look like
```py
# some init stuff whatever
client.run(token)```
#

I think session closing is async but I don't remember

#

!d aiohttp.ClientSession.close

unkempt canyonBOT
vale wing
#

Yeah it's coro

#

Why await

#

Eh wait

#

That's very weird cause I used it in a similar way and got no deprecation warnings

#

Maybe I've confused something

#

No wait

#

What version of aiohttp you have

#

What exactly

#

Is it 3.8.3 or another

#

pip freeze

#

Interesting

#

Ok send the whole code please

slate swan
#

Aye, im not familiar with JSON, so i have a dict, and if my message has a word which is any of those keys, it should print the value,

but in the JSON file, the dict has no name, so how will I call it?

slate swan
#

narrators.py


#DICT
narrators = {
            ("e"): "a"
            }

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

    json.dump(narrators, f)``

**narrators.json**```
```{"e": "a"}```
**cmds.py** [cog]
```import discord
from discord.ext import commands
import json

file = json.load(open('narrators.json'))
narrators = file.get('narrators')

class cmds(commands.Cog):
    def __init__(self, client):
        self.bot = client

    @commands.Cog.listener()
    async def on_ready(self):
        print("CMD Cog working")

  # RIJAL COMMANDS BEGIN HERE:

    @commands.command()
    async def rijal(self,ctx, message:str):
      if message in narrators.keys():
         await ctx.send("e")




  # RIJAL COMMANDS END HERE

async def setup(client):
    await client.add_cog(cmds(client))```

**main.py**
```from discord import Intents
from discord.ext import commands
from TOKEN import token
import asyncio
import os
intents = Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='!',intents=intents)

@client.event
async def on_ready():
    print("RijalBot online")

async def load():
    for file in os.listdir('./commands'):
        if file.endswith('.py'):
            await client.load_extension(f'commands.{file[:-3]}')

async def main():
    await load()
    await client.start(token)

asyncio.run(main())```

Im trying to get it so if I send a message, it checks if the message is a key in the json dict, so I did !rijal e, but I got nothing, not even a traceback
serene pagoda
#

Can someone help

serene pagoda
#

Think I figured it out

terse coyote
#

how to get info from discord.ui.TextInput?

slate swan
#

Hey, how do I make it where after the program picked a random place to work at and a random paycheck how do I log that? (discord bots experts)

naive briar
unkempt canyonBOT
slate swan
#

and I'm trying to add there balance and etc

naive briar
#

Just pick random item then store it in a variable

#

!e

import random

meows = ("meow", "mau")
item = random.choice(meows)

print(item)
unkempt canyonBOT
#

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

meow
slate swan
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.

By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

slate swan
#

!e 3.10 ```py @commands.command()
@commands.Cooldown(1, 20, commands.BucketType.user)
async def work(self, ctx):

    place = ["Mc Donalds",
            "Burger King",
            "Checkers",
            "Zembay PD",
            "Zembay FD",
            "Zembay DOT",
            "Zembay National News Station"
            ]
    
    
    Money = [ 150,
            130,
            400,
            900,
            1000,
            40,
            1,
            60,
            30,
            20,
            950,
            12,
            32,
            43,
            12,
        
    ]
    
    Balance = random.choice(Money, place)
    
    await ctx.author.send(f"You worked at {random.choice(place)}, and you got {random.choice(Money)}")```
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     @commands.Cooldown(1, 20, commands.BucketType.user)
003 | IndentationError: unexpected indent
slate swan
fading marlin
#

nice data base ducky_sphere

naive briar
#

It's just

mn = random.choice(Money)
rt = random.choice(place)

await ctx.send(f"You got {mn} from working at {rt}")

# do anything with it
slate swan
naive briar
#

Use the variable

#

Common sense

lucid jolt
#

is it safe to run a discord bot on replit

slate swan
desert heart
#

See the discord bot hosting thread for more details on that.

lucid jolt
#

is there free options to host

#

im gonna go there

torn sail
lucid jolt
#

a year yeah

torn sail
#

but all permantly "free hosts" always have something not good about them

#

for example replit has the ratelimiting stuff

flint bolt
#

hey, ive got a problem

lucid jolt
#

what

flint bolt
#
@bot.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
    await ctx.message.delete()
    await asyncio.sleep(1)
    await ctx.channel.purge(limit=limit)
    await asyncio.sleep(1)
    purge_embed = discord.Embed(title='Purge [!purge]', description=f'Successfully purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
    purge_embed.set_footer(text=str(datetime.datetime.now()))
    await ctx.channel.send(embed=purge_embed, delete_after=True)```

it purges the messages with the int i set, but it doesn't send the embed after purging
lucid jolt
#

remove delete_after and then try it to tst

flint bolt
#

yep, works now, thanks

outer violet
#

Is it possible to edit a bots previously sent message by using the message id? And if so, could I get an example of how it would look like?

vocal snow
#

But are you trying to edit a very specific message?

flint bolt
#
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
import asyncio
import datetime
intents = discord.Intents.all()
from discord import app_commands
help_command = commands.DefaultHelpCommand(
    no_category = 'Commands'
)


client = discord.Client(intents=intents, description = 'Welcome to Nucleus! The multifunctional discord bot made by Technoglave', help_command = help_command)
tree = app_commands.CommandTree(client)
member = discord.Member

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=1056934892392419329))
    await client.change_presence(activity=discord.Game(',help ┃ Created by Technoglave'))
    print(f'{client.user.name} has connected to Discord!')
    
@tree.command(name = "ping", description = "ping command", guild=discord.Object(id=1056934892392419329)) 
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message("Pong!")

@tree.command(name='commands', description='List commands', guild=discord.Object(id=1056934892392419329))
async def listcommands(interaction: discord.Interaction):
    await interaction.response.send_message(f"For Fun commands: ,fun;\nFor server info: ,info")

@tree.command(name='warn', description='Warn a user', guild=discord.Object(id=1056934892392419329))
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason=None):
    await interaction.response.send_message(f"{member.mention} was warned for {reason}")

code shows this error:

torn sail
flint bolt
#

now showing this:

outer violet
vocal snow
#

You'll need the channel ID too

#

get the channel with bot.get_channel --> fetch the message with channel.fetch_message --> edit it with message.edit

outer violet
#

Ahh okay

#

Thank you :)

hushed galleon
outer violet
#

I see

#

Thank you as well pithink

silent ermine
#

How do I unban every user in the ban list of discord? I was thinking of using a for loop with ctx.guild.members but that wont get the guild bans.

vocal snow
#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
silent ermine
# unkempt canyon

And then I can do entry.unban() or would it be entry.user.unban()?

rugged shadow
silent ermine
tropic estuary
#

how to like generate nested objects in json ? for an inventory.

upbeat otter
#

easy as that

primal cliff
#

how do I edit the status of a bot?

tropic estuary
#

why does json make images[0] "/"

#

oh the variables are different..

#

;-;

tropic estuary
#

@client.event
async def on_ready():
  change_status.start()
  print("online!")

hollow agate
#

🥄

#

& don't use on_ready for anything. setup_hook exists

#

on_ready can be called multiple times, while setup_hook doesn't.

tropic estuary
hollow agate
naive briar
#

In general

hollow agate
tropic estuary
#

now when i do this it overwrites

#

the inventory of an user

#

how do i fix this

vocal snow
tropic estuary
vocal snow
#

I don't understand why you're setting data = {} after loading it from the json either

tropic estuary
#

hm.

#

e.

tropic estuary
vocal snow
#

what

#
x = 1
x = 2
print(x)
``` what will this print
tropic estuary
vocal snow
#
data = json.load(f)
data = {}
``` same thing is happening here.
tropic estuary
#

it gives an key error

#

for some reason

vocal snow
#

so str(user_id) isn't in the dict

#

so you should add it to the dict only if isn't there already

tropic estuary
#

heH?

vocal snow
#

you add str(user_id) to the dictionary

tropic estuary
#

yuh?

vocal snow
#

if it is not in the dictionary

tropic estuary
#

then key error?

vocal snow
#

if it is already in the dictionary and you set it to {}, then you're overwriting it

tropic estuary
vocal snow
#

now what is the value of data

naive briar
#

Dictionary 📕

tropic estuary
vocal snow
#

yes, so it's your json data

#

so if str(user_id) is in that dict, you will get the corresponding user data

#

if it's not, you'll get a KeyError

#

which is why you should ensure that str(user_id) is in the dict before trying to access it...

slate swan
#

rf

jagged adder
#

does anyone know how to lock (not just archive) discord threads via a discord bot? ive tried searching the docs and im not havin much luck

light violet
#

with open(filename, 'w',1) as f:
for i in range(1024):

#

how is there indent error

naive briar
#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

frail notch
#

Hi there, how can I get my bot's commands to show up in the / menu?
At the moment the commands work but don't appear or function as slash commands and I'm unsure how to change that.

import asyncio
import discord
from discord.ext import commands

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

client = commands.Bot(command_prefix='/', intents=intents)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    channel = client.get_channel(1059413596372729909)
    guild = client.get_guild(1059392729286709298)
    await guild.create_role(name='Support Team')
    await guild.create_role(name='Muted', permissions=discord.Permissions.none())
ticket_counter = 0

@client.command()
async def ping(ctx):
    await ctx.send('Pong!')
naive briar
#

That's not how you create slash commands

frail notch
#

Could you link me to a doc?

#

or something plz

naive briar
#

There's a walkthrough in the pins

frail notch
#

alr

#

ty

shrewd fjord
#

banned_users isnt a list to iterate xd

#

yes

#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
shrewd fjord
#

here are the examples if u r wondering

slate swan
#

Im not gettting any traceback, my command simply doesnt work?


#DICT

# THIQA AND OTHER
weak = "Weak"
thiqa = "Reliable"
unknown = "Unknown"
semi = "Some accepted."

# OTHER
narrators = {
             #ABAN B. ABI AYYASH
             "Abān b. Abī ʿAyyāsh": weak
}

with open('rijaldata/narrators.json', 'w') as f:
   json.dump(narrators,f)```

from discord.ext import commands
import json

narrators = json.load(open(r"C:\Users\intel\Desktop\rijalbot\rijaldata\narrators.json"))

class cmds(commands.Cog):
def init(self, client):
self.bot = client

@commands.Cog.listener()
async def on_ready(self):
    print("CMD Cog working")

RIJAL COMMANDS BEGIN HERE:

@commands.command()
async def rijal(self,ctx, message):
  val = narrators.values()
  weak = "Weak"
  if narrators.keys() in message:
     await ctx.send("e")

RIJAL COMMANDS END HERE

async def setup(client):
await client.add_cog(cmds(client))```

#

I need it to check a dictionary, if the message contains a key from the dictionary, it needs to check its value, and if its value equals something I specify, it should message something

sweet urchin
#

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.

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.

glossy flame
#

If another bot, such as MEE6, were to say a certain keyword, is it possible for my bot to be able to react to it? I know that commands aren’t possible for bots, I wanted to see if it was the same for simple listens

naive briar
#

Use on_message event

#

Read the error

#

How can you possibly get every error that shouldn't be possible to get

glossy flame
vocal snow
#

yes

#

on_message picks up all messages that are visible to the bot

#

where did you get .fetch_premium_subscription from

#

The docs contains a list of attributes and methods that you can use

#

don't access an attribute which doesn't exist

unkempt canyonBOT
#

Hey @sand falcon!

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

sand falcon
#

ping when reply

slate swan
#

When you define bot slash commands object is imported with it

#

As an attribute

sand falcon
#

ok also i am using pycord

sand falcon
slate swan
#

Ewww

sand falcon
#

after removing

slate swan
#

Who uses pycord 💀

sand falcon
#

whats wrong with pycord?

slate swan
#

Menace to society

slate swan
sand falcon
#

oh

sand falcon
slate swan
sand falcon
#

and nothing changed

flint bolt
#

hey, ive got an issue
so i have this warn embed that im looking to send to not just the slash command interaction response, but also to the dm's of the user who got warned so they know that they have been warned
but for some reason, the dm function returns this error:
discord.app_commands.errors.CommandInvokeError: Command 'warn' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
code attached:

@tree.command(name='warn', description='Warn a user',)
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    await interaction.response.defer(ephemeral=True)
    warn_embed = discord.Embed(title='Warning', description=f'Successfully warned {member.mention} for {reason}.', color=discord.Colour.og_blurple())
    warn_embed.set_footer(text=str(datetime.datetime.now()))
    await interaction.followup.send(embed=warn_embed)
    user=client.get_user(member)
    await user.send(embed=warn_embed)
slate swan
#

Aye, tryna get my bot to check if the message content contains any keys, when I do !rijal a, it gives me nothing

    async def rijal(self, ctx):
     for key in narrators.keys():
        if key in narrators.keys() == ctx.message.content:
          await ctx.send("e")```
unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
#

narrators.json

{"a": "Weak"}

upbeat otter
#

and you don't wanna do that

#

since here you can simply do member.send

flint bolt
#

oh

#

alright let me try

upbeat otter
#

you need not get a User object when you already have a Member object since they both have same attributes (Member has guild related information also)

flint bolt
#

great, works, thanks

flint bolt
upbeat otter
upbeat otter
flint bolt
#

lol

fickle hamlet
#

Can’t you just do content in narrator

hushed galleon
upbeat otter
#

hm well, that too

upbeat otter
pulsar kettle
#

Hey guys, I'm developing my first Discord bot and was curious on whether I should code it with custom commands (e.g. !kick @pulsar kettle) or use Discord's slash commands (/kick @pulsar kettle), any thoughts?

flint bolt
#

slash commands

#

but if youre doing a first

#

actually yeah if tyoure doing a first you should do it through custom commands

#

since slash commands are a bit more complicated

pulsar kettle
#

Yeah because I coded like 7-ish custom commands then realised slash commands exist aha

#

I'm able to rewrite it for slash commands if needed

vocal snow
#

If you're planning on growing your bot to 100+ servers (which requires verification) then you'll need to switch to slash commands

vale wing
#

If you are a beginner and want to do slash, use disnake, if you are a lazy person and want to do slash, use disnake, if you want text commands, use whatever (disnake), if you are a tryhard, use dpy

flint bolt
#

also on that, im looking to fetch the server's name in my code and i can't really seem to find how to do it. can anyone show?

@tree.command(name='warn', description='Warn a user',)
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    warn_embed = discord.Embed(title='Warning', description=f'Successfully warned {member.mention} for {reason}.', color=discord.Colour.og_blurple())
    warn_embed.set_footer(text=str(datetime.datetime.now()))
    await interaction.response.send_message(embed=warn_embed)
    warn_embed = discord.Embed(title='Warning', description=f'{member.mention}, you have been warned on {SERVER NAME HERE}.')
    await member.send(embed=warn_embed)```
pulsar kettle
#

I tried out slash commands by rewriting my ping command and here's what I had:

async def ping(interaction: discord.Interaction):
    await interaction.response.send_message('pong!', delete_after=5)```
pulsar kettle
vocal snow
#

you could write it for both, but note that discord won't give you access to the message content intent just for the purpose of commands (when you verify your bot)

pulsar kettle
#

So it's better to just focus on slash commands?

vocal snow
#

Probably. It will be less limiting

pulsar kettle
#

Alright cool, thank you for your help guys <3

flint bolt
flint bolt
#

its just @tree.command

golden portal
#

the decorator is callable

pulsar kettle
vocal snow
flint bolt
#

oh i didnt know that

golden portal
#

its not really hard to make both slash and text commands compatible, you could just use hybridcommand, and it would use the respective methods depending on if its slash or text internally, the interface stays the same

flint bolt
#

breh

slate swan
#

So I did what you told me, just changed a little

from discord.ext import commands
import json

with open(r"C:\Users\intel\Desktop\rijalbot\rijaldata\narrators.json") as f:
    narrators = json.load(f)



class cmds(commands.Cog):
    def __init__(self, client):
        self.bot = client

    @commands.Cog.listener()
    async def on_ready(self):
        print("CMD Cog working")

  # RIJAL COMMANDS BEGIN HERE:

    @commands.command()
    async def rijal(self, ctx):
        keys = narrators.keys
        if ctx.content in keys:
          await ctx.send("e")

# RIJAL COMMANDS END HERE

async def setup(client):
    await client.add_cog(cmds(client))```

but when I do !rijal a, it still doesnt do anything
#

json
{"a": "Weak"}

naive briar
#

!d dict.keys

unkempt canyonBOT
#

keys()```
Return a new view of the dictionary’s keys. See the [documentation of view objects](https://docs.python.org/3/library/stdtypes.html#dict-views).
naive briar
#

.keys is a method, so call it

mental hollow
#

what is ctx.content?

naive briar
#

Also your check is kinda useless

slate swan
#

Hm?

naive briar
#

Since you're checking if the exact whole message content is in the dictionary

slate swan
#

Ah

naive briar
#

!e

d = {"a": 0}
print("a " in d.keys())
unkempt canyonBOT
#

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

False
slate swan
#

If I wanted to check if a word was present in the message, i'd reverse the statement?

oblique root
#
async def check_date():
    while True:
        now = datetime.datetime.now()
        if now.day == 1:
            await start_monthly_event()

        if now.day == 1 or 15:
            await start_biweekly_event()

        await asyncio.sleep(86400)

what is the correct way to have the bot check for 2 different days for the biweekly event?

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!

naive briar
#

He's sleeping using asyncio.sleep, so no exactly

pulsar kettle
#

Trying to implement slash commands into my Discord.py bot, the following command adds the mute role to the member and sends the embed as intended, however it doesn't remove the mute role after the time is up. Can somebody help please?

@bot.tree.command(name='tempmute', description='Temporarily mutes a member')
@has_permissions(kick_members=True)
async def tempmute(interaction: discord.Interaction, member: discord.Member, time: str=None, reason: str=None):
    desctime = time
    guild = interaction.guild
    mutedRole = discord.utils.get(guild.roles, name="Muted")
    time_convert = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "mo":18144000, "y":31536000}
    tempmute= int(time[:-1]) * time_convert[time[-1]]
    if not mutedRole:
        mutedRole = await guild.create_role(name="Muted")
        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
    await member.add_roles(mutedRole, reason=reason)
    embed = discord.Embed(title=(f'***{member} has been muted for {desctime}*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)
    await member.send(f"You have been temporarily muted from: ***{guild.name}*** for **{desctime}** | {reason}")
    await asyncio.sleep(tempmute)
    if mutedRole in member.roles:
        await member.send(f"You have been unmuted from: ***{guild.name}***")
        await member.remove_roles(mutedRole)
naive briar
#

But yeah, task loop is also a great choice

#

!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").
oblique root
#

so it is checking for it, that's not the issue, what is happening, and sorry for not explaining enough in my question, is it thinks every day is "1" for the biweekly, so it is triggering on every day

naive briar
#

In the time argument, you can give it exact time to run

#

!d datetime.time

unkempt canyonBOT
#

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
All arguments are optional. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
naive briar
#

Or just make it run every day and check the day Ig pithink

oblique root
#

i think that is the issue, the reloading of the bot lol

flint bolt
#

is there any way i can add an image/gif to my discord bot's activity?

#

no i mean as in my discord bot is playing an activity and i want to see if i can add an image to that playing activity

oblique root
#

thanks everyone who pointed me in the right direction, it is working as intended now.

flint bolt
#

alright lmao

oblique root
#

i am a grade below novice when it comes to python, i wish i could help ya, but i don't think i can

#
bad_word_count = open("bad-word.json")
in_memory_word_count = json.load(bad_word_count)
```py

def write_word_count_to_list(in_memory_word_count):
with open('bad-word.json', mode='w') as f:
json.dump(in_memory_word_count, f, indent=2, sort_keys=True)

def add_words(user):
try:
with open("bad-word.json", mode="r"):
in_memory_word_count[f'{user.name + user.discriminator}'] = int(in_memory_word_count[f'{user.name + user.discriminator}']) + 1
write_word_count_to_list(in_memory_word_count)

except KeyError:
    with open("bad-word.json", mode="r"):
        in_memory_word_count[f'{user.name + user.discriminator}'] = 1
        write_word_count_to_list(in_memory_word_count)

def check_words(user):
with open("bad-word.json", "r") as total_words:
total_words_data=json.load(total_words)
return total_words_data


this is how i updated a json file in my last discord bot
#

yeah, i don't know what im doing

#

i am literally having chat gpt explain things to me in steps, and sometimes have to have them explain it to me as if i were 5

naive briar
#

ChatGPT doesn't know everything and it can give incorrect information

oblique root
#

i don't like the way it codes most of the time, but it usually gives me something i can work with haha

#

my favorite thing about chat gpt is the lists it can make me for json files, i am building an art themed discord channel, so character generators are fun, and in the past i had to think of all the words, now chat gpt spits out list without hesitation

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
#

how do i stop cloudlfare from blocking my bot

#

import discord

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_message(message):
if message.content == '!test':
await message.channel.send('This is a test')

client.run(''LOLIMNOTGIVINGUMYBOTTOKENLOL')

naive briar
#

You're spamming something or using replit

#

Also reset your bot token if that is what you just sent

unkempt canyonBOT
#

@nimble cradle Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

slate swan
#

no i took some of the token code outand replaced it with LOLIMNOTGIVINGUMYBOTTOKENLOL so theres no way u can get into the bot and also im using a test server too so u cant nuke it or anything even if u did find the token

vale wing
tawny arrow
#

hey guys, im getting this cloudflare error
things i've tried :
1.) kill 1
2.) created a new application on discord developer portal
but it didn't work.
also, im using uptimerobot to keep my bot running 24/7

vale wing
#

When the replit

#

Replit is impossible to use for hosting bots yall should already know

naive briar
#

Most of them don't

vale wing
#

!replit

#

Sus

slate swan
#

Whats the easiest way to check if a message contains a key from a json dict?

vale wing
#

Maybe better to formulate it like "any of dict keys is in message"?

#

Code looks like the phrase in that case

any(k in message.content for k in your_dict)```
upbeat otter
vale wing
#

Replit hacker 🥶

tawny arrow
#

😭

vale wing
#

I've been looking for hosts in Russia recently, we got no "free trial" options but hey there are pretty nice options just for 3$

upbeat otter
vale wing
#

I am eligible but I doubt they would recognise hand-written text on my student ID and we don't have mails

#

Also hosting service will ask for card verification anyway most likely

vale wing
#

Man I am in Russia

#

You can no longer use russian cards outside of Russia 😩

#

I have one from bank that's not under sanctions yet it doesn't work too

upbeat otter
#

no offence

vale wing
#

at least it's not ohio

vale wing
# upbeat otter tf is happening in Russia 💀

I am not into politics, economics and other unpleasant stuff (that's not the channel topic anyway) but from what I know we just got disconnected from SWIFT which does international payments and visa and mastercard stopped handling international transactions between Russia and other countries, we only got russian Mir payment systems that is accepted in some CIS countries

upbeat otter
#

oh

vale wing
#

Google/apple pay don't even work, we have MirPay and SberPay

upbeat otter
vale wing
#

Of course you haven't

#

That's exclusive for Russia 😉

upbeat otter
fresh wigeon
#

guys i am new at making a discord bot can you give me the basic code cuz i want to learn. Thanks😀

slate swan
fresh wigeon
#

yea

slate swan
fresh wigeon
#

thanks

upbeat otter
#

check if you have multiple python instances running, if not that, regen your bot's token

slate swan
#

or maybe a process_commands inside a listener

slate swan
#

What arguements did you give

#

Can discord bots read a json with spaces in its keys?

#

Mine doesnt work if I dont use a key without spaces

craggy sleet
#

hey guys! super quick question, what library should i use to create select menus? or do you not need another library and can do them in discord.py itself?

sick birch
#

Here let me get the link for the example I wrote

upbeat otter
sick birch
light violet
#

how can i take the rest of the sentence whole as an arg?? lie if i type . search this and that, it is only accepting the first word ie this as the arg how to make the arg as this and that

slate swan
# upbeat otter well that should be possible, doesn't make a difference
    async def rijal(self, ctx, message):
      weak = "weak"
      unknown = "unknown"
      if narrators[message] == weak:
       await ctx.send("This hadith is **unreliable**")
      elif narrators[message] == unknown:
        await ctx.send("This hadith is **unknown**""E")
      elif narrators[message] in unknown and narrators[message] in weak:
          await ctx.send("This hadith is **unknown** and **unreliable**")```

^^^ why cant my code read a key without a space? if my key is a:1

it works fine, but if it is " a a":1, it doesnt give anything
upbeat otter
#

it's completely fine to have spaces

light violet
#

man pls help me how do i take the whole rest of the message as an arg

upbeat otter
#

and where is it erroring, specify the line

slate swan
upbeat otter
slate swan
#

Because when the key has no spaces, it sends the messages, but when it has spaces, it doesnt

upbeat otter
#

is message the key you're searching for?

slate swan
#

Nah, im checking if the message is a key

upbeat otter
slate swan
split forge
#
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 108, in __getattr__
    raise AttributeError(msg)
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```
mental hollow
#

does jsk not work when creating buttons? like it just don’t create the button whatsoever?

#

I’m trying to jsk some code with a view which has some buttons, im passing the view when sending the message yet I’m still not getting my buttons

sick birch
spring flax
#

Kind of basic here but anyone know why I get this error

cloud dawn
#

Is the config inside the "classes" directory?

#

@spring flax

spring flax
#

nope

cloud dawn
#

Well you are doing a relative import so if you don't have from then it will now look for config.py inside the executed folder.

spring flax
#

but i can't use from

#

many of my relative imports don't work actually

cloud dawn
#
C:.
│   config.py
│
├───bar
│   │   bot.py
│   │   cheese.py
│   │
│   └───yes
│           lol.py
│           __init__.py
│
└───foo
``` With this tree; if we launch from `bot.py` we can import `cheese.py` by doing `import cheese` or import `lol.py` using the `from` keyword. Keep in mind you need `__init__.py` for Python to see the directory. An empty one is fine.

Now we can import lol by typing `from yes import lol`. Here there also is a file called `config.py`. This package is called a top level package because it's higher than the executed file. Generally you don't want to import top level packages since it's not pretty. It's also a security risk.

I recommend to put the config lower or the bot higher. @spring flax
slate swan
#

How would I get this to check messages even if they are in others? If I do !hadith (msg), it will run fine, but if its !hadith (msg other text) how can I get it to run? How can I get it to check if the key is in the msg?

    async def hadith(self, ctx, *,  message):
      weak = "weak"
      unknown = "unknown"
      if narrators[message] in message == weak:
       await ctx.send("This  is **unreliable**")
      elif narrators[message] == unknown:
        await ctx.send("This  is **unknown**")
        await ctx.send(narrators.values(unknown))
      elif narrators[message] in unknown and narrators[message] in weak:
          await ctx.send("This  is **unknown** and **unreliable**")```
#

Heres my json

#

{"Aban": "weak"}

#

hey I need help

near wolf
slate swan
#

I deleted nextcord

#

@near wolf

near wolf
slate swan
#

Okay

#

@near wolf

slate swan
#

Hello, can somebody help me how to make discord bot send dms from user to a selected channel?

cloud dawn
#

The user would need to also assign the channel id.

cedar snow
#

and a guild ID preferably 😉

slate swan
#

It's about a kind of ticket. To send a user's message to the bot after being sent on a private message, it was sent by the bot to the channel indicated by me

cloud dawn
cedar snow
twilit scarab
#

Does anyone of you using cogs does have a decent button example for me?

slate swan
#

How can I check if a key from a dict is in a message string?

#
    async def test(self,ctx, *, message):
        keys = narrators.keys()
        for keys in narrators:
            if keys in message:
                await ctx.send("e")```
#

However, it doesnt work

#

{"Aban": "weak"} heres the json dict

cloud dawn
cloud dawn
cloud dawn
cedar snow
cloud dawn
slate swan
cloud dawn
cedar snow
#

for sure, I was thinking like a minute

cloud dawn
twilit scarab
#

I tried it this way;

 @cog_ext.cog_slash(description="Kreiere einen Button!")
    async def button(self, ctx: interactions.CommandContext):
      button = interactions.Button(style=interactions.ButtonStyle.PRIMARY,label="Click me!",custom_id="click_me")
      await ctx.send(components=button)
slate swan
cloud dawn
slate swan
twilit scarab
cloud dawn
twilit scarab
#

i had it running with components.. a shame they removed it

pliant gulch
#

Isn't keys() kind of redundant

#

Also this can be made much easier because you require them as tokens

cloud dawn
twilit scarab
#

Thanks ill give it a go

cloud dawn
pliant gulch
#
@command(...)
async def foo(ctx: Context, *message: str) -> None:
    if intersection := (set(message) & narrators.keys()):
        ...
#

*message captures each word and appends to a sequence

#

Rather than needing to do split

cloud dawn
#

Andy slow down you're using 4/5 new things for them rn 😂

#

But I agree nonetheless.

slate swan
cloud dawn
slate swan
#

Ah didnt see that

#

Thanks, both of you

cloud dawn
pliant gulch
#

set intersection for that sweet sweet O(min(len(s), len(t)))

slate swan
slate swan
cedar snow
slate swan
#

that's not related, it wouldnt trigger that LOC

slate swan
cedar snow
#

that doesn't matter

#

but yeah, having third-party ~forked discord libs installed can mess things up => delete them all & reinstall dpy

slate swan
#

Lol autocorrect

pliant gulch
#

Is this another discord_slash moment

#

Does pycord do the same

cedar snow
cedar snow
slate swan
cedar snow
#

hmm

#

nextcord is one of the issues
seems like you tried a previous shitty tutorial too 😉

slate swan
#

Also trying it to send the key that was found in the message, but it doesn tseem to work

     if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
        await ctx.send("e")
     elif any(unknown for unknown in ctx.message.content.split() if unknown in narrators.keys()):
        unknown = "unknown"
        test = unknown in ctx.message.content.split()
        await ctx.send(test)```

json

```{"Aban": "weak", "test": "unknown"}```
#

use venvs to avoid such mess

#

!venv

unkempt canyonBOT
#
Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
cedar snow
cedar snow
# slate swan so what should I do?

2 options
either use venvs (you should learn them, the sooner the better)
OR
delete all python discord bot related libs and only keep the dpy one in your pip list

#

I opt the former

slate swan
#

Sorry for caps^^

cedar snow
slate swan
#

Oh

cedar snow
# slate swan Got no errors

debugging ~trying to understand what the for loop is iterating over etc, chances are, it isn't what you think it is

#

also, can you tell us what "message" you tried to type AND what should happen? / what the intended purpose is

frail notch
#

How can I log the full command ran with my bot? At the moment I have py @client.event async def on_command(ctx): channel = client.get_channel(1059393082237403156) server = ctx.guild.name user = ctx.author cchannel = ctx.channel command = ctx.command await channel.send(f'`{user}` used `{command}` in `{server}` in `{cchannel}`')
But I want it to also log the peramaters (e.g *ban user1 10d)

cedar snow
#

example
!test shit should make the bot respond with "shit"

#

have you looked at ctx's attributes?

#

in the docs

frail notch
cedar snow
#

hint: something with "command"

slate swan
#

What does venv even do

frail notch
#

got it, message_content

slate swan
cedar snow
#

why aren't you using your *, message parameter?

slate swan
cedar snow
#

if any(key for your_dict.keys() in message.split(" "):
maybe that'll clear some things up ⏫

#

or even better, if you instantly want the value, related to the key

for key in your_dict.keys():
  if key not in message.split(" "):
    continue
  await ctx.channel.send(f"The key found was {key}, the relating value is {your_dict[key]}")
  return```
#

there's obviously more efficient ways of doing this (by for example using := and the .get() method on a dict, also splitting the message on every iteration is shit), but this is just for educational purposes

slate swan
#

The problem with the for key in etc is that im not looking for one specific key, rather, im looking for all keys that are present in the message

cedar snow
cedar snow
#

again, there are more efficient ways of doing this (by intersecting between 2 sets)...

young dagger
#

How do you check for users who reacted to a message?

#

I tried this but it returns empty list everytime

users = await message.reactions.get(emoji).users().flatten()

cedar snow
young dagger
cedar snow
cedar snow
#

lastly, any error handlers by any chance?

cedar snow
#

you need to refetch the message, not sure

#

also, as stated, flatten is deprecated

cloud dawn
#

For 14 years already lemon_zipped

near wolf
cedar snow
#

lastly, a giveaway command is VERY delicate and you have to take a lot of stuff into account:
one of them being "what if your bot restarts?"
think about that

young dagger
cloud dawn
#

But..

#

Then you need to go back and redo it anyways..?

cedar snow
#

right, you're only making it harder for yourself

young dagger
#

I want to understand why it doesn't pick a winner

cedar snow
#

most likely because you need to refetch the message

young dagger
#

Even though there are users who reacted to the message

cedar snow
#

test = await test.channel.fetch_message(test.id)

#

THEN get the reactions of that message

#

I know, shitty variable names, but you get the point

#

you're trying to get reactions of the message when you sent it, not after the sleep/timer hits 0

slate swan
#

Hello, i need to create ticket system in dm with bot. Can somebody help me? (.py)

cedar snow
slate swan
#

ok, ty for helping

cloud dawn
#

I'd use task and check at 12pm if there is a giveaway that needs to end then put that in a task. If the giveaway isn't today I wouldn't even bother to add it.

cedar snow
#

lastly, you should also check for giveaways which ended while the bot was offline

cloud dawn
#

... that can be done by assigning a giveaway id then also saving the message id and the end time. Then get the times on startup, using a query you can get the ones that are less than a day or expired.

frail notch
#

How can I fix this?

Defaulting to user installation because normal site-packages is not writeable

ERROR: Could not find a version that satisfies the requirement discord-components

ERROR: No matching distribution found for discord-components

81718e89734b:~$ python --version
Python 3.8.8
cedar snow
#

why are you trying this command in the first place?

frail notch
#

To install discord-components

cedar snow
#

where did you get that from?

cloud dawn
#

discord-components doesn't work with that Python version. It's also an archived package and hasn't been updated in a year or so.

frail notch
#

oh

cedar snow
#

most likely a YT tutorial lemon_angrysad

frail notch
cloud dawn
frail notch
#

ok

cloud dawn
cloud dawn
young dagger
cedar snow
cloud dawn
#

flatten will give error.

cloud dawn
#

I'd also use a specific emoji to avoid strange stuff.

young dagger
cedar snow
#

also, when picking a random user, I wouldn't async iterate through the whole list for that tbh

cloud dawn
cedar snow
cloud dawn
#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
proud tiger
#

Help

cedar snow
#

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

proud tiger
cedar snow
proud tiger
#

Here

cedar 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. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

proud tiger
cedar snow
proud tiger
#

Its Not do you wanna See the code

cedar snow
#

well, I'm telling you it should be

#

from discord import Intents
that's the correct import

#

as shown above by the bot

proud tiger
#

I wrote it lowercase

cedar snow
#

it shouldn't be written in lowercase

#

🧠

cedar snow
proud tiger
#

Oh,thank you for helping me i try it again.

slate swan
#

Help please

cedar snow
#

you're just blindly copy pasting whatever works for you, right?

slate swan
#

I'm not

#

I'm watching a tutorial on how to make a ticket system

cedar snow
slate swan
cedar snow
cedar snow
#

every command used in this channel which makes the bot say something is for a reason

slate swan
cedar snow
#

dpy changes (updates / has breaking changes )too often to make YT tutorials reliable, they're outdated quickly

slate swan
#

No wonder why every tutorial I follow I mostly get a error lol

cedar snow
#

makes sense

cloud dawn
#

Just filter last 3 months should be alright.

slate swan
cedar snow
#

they also use libraries etc which we don't use, so if you're asking for help, chances are way smaller of finding some, because we don't use third-party libs on top of the official dpy lib

proud tiger
#

@cedar snow Had to fix a bit of my code it works now thanks!

cloud dawn
#

Too bad there isn't a tutorial that fully does it correct.

cedar snow
slate swan
#

@cedar snow I found out why I got the error on "no imports discord.enum" its because I had another folder called discord bot

#

but now I have a different error

slate swan
cedar snow
#

you've basically copy pasted someone else's code... ofc debugging will be hard then

cloud dawn
#

I think you also putted a slash command in a View class and put random variable tree there.

#

Remove the things you copy pasted and send the whole bot I see it's not long, let's see if that's correct first.

#

Let's build from there.

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
#

well I fixed it but I have an bug now

#

there is no slash commands

#

@cedar snow how could I fix this?

cloud dawn
#

Seperate the command and the View class.

slate swan
#

Okay

proud tiger
#

!Intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

slate swan
#

@cloud dawn but wait if I separate the commands from the class "ticket_launcher" wouldn't not work?

slate swan
cloud dawn
#

Error?

slate swan
#

There is no error

#

The bot successfully gets on but the slash commands don't work

#

what should we do

#

???

sick birch
# slate swan

the whole function and its decorator should be indented so it's in the class

#

The ticket function, I should clarify

cloud dawn
#

Slash command also doesn't get synced anywhere.

slate swan
cloud dawn
# slate swan

Also I don't mind it a lot but asking for 3th party payments is against Discord's ToS. Might be careful with that one.

pliant gulch
#

That's not syncing

young dagger
#

How can I add this?

pliant gulch
#

@button

cloud dawn
#

Thank R. Danny

#

@slate swan, I don't recommend copying the code.. like you can see there are a lot of things that needs fixing and it can take awhile.

slate swan
#

How do I fix this???

#

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents= discord.Intents.default())
        self.synced = False
    
    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id=1059268830209257612))
            self.synced = True
        print("we are logged in!")
            
            
client = aclient()
tree = app_commands.CommandTree(client)
            
            
            
@tree.command(guild = discord.Object(id=1059268830209257612), name = 'ticket', description="you could purchase stuff!")
async def ticketing(interaction: discord.Interaction):
    embed = discord.Embed(title="✘'𝘀 𝗦𝘁𝗼𝗰𝗸𝘇 - Purchase", description="""Payment Methods: 
:paypal: :cashapp: :crypto: 

How does it work?
- Press the purhase button below. 
- Describe the amount you want to purchase.
- Describe the payment method you want to use for the deal.
- Wait until staff helps you with your deal.
- When the deal is done: you will get customer role and you can vouch.

Minimum Amount When Purchasing: 5$""", colour=discord.Color.purple())
    await interaction.channel.send(embed = embed, view = ticket_launcher)
    await interaction.response.send_message("Tickin", ephemeral= True)````
buoyant quail
#

show what ticket_launcher is

slate swan
#

Howd I create a list from all keys found in my message?

If my message contains a few keys, i need them added to a list

#

Right now, I got something like this

    async def test(self,ctx, *, message):
     if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
        weak = "weak"
        found = weak in narrators.keys()
        await ctx.send(found)
        await ctx.send("e")```
buoyant quail
#
found = [weak for weak in ctx.message.content.split() if weak in narrators.keys()]
slate swan
#

@buoyant quail

buoyant quail
#

ticket_launcher()

slate swan
#

I should of thought of that lmao, thats elegant. Thanks alot man:

#

One last thing, how would I go on removing the sqr brackets and quotes?

buoyant quail
#

!d str.join

unkempt canyonBOT
#

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

!e

arr =  ["a", "b", "c"]
print("---".join(arr))
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

a---b---c
slate swan
#

@buoyant quail I have another error

#

it does not create the ticket channel

#
class ticket_launcher(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout= None)
        
    @discord.ui.button(label = "Perchase!", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
    async def ticket(self, interaction: discord.Interaction, button: discord.ui.button):
        ticket = utils.get(interaction.guild.text_channels, name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
        if ticket is None: await interaction.response.send_message(f"you already have a ticket open at {ticket.mention}!!!", ephermeral = True)
        else: 
            
            
            overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
                interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files = True, embed_links = True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel=True, send_message = True, read_message_history=True)
            }
            channel = await interaction.guild.create_text_channel(name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}", overwrites= overwrites, reason=
            f"Ticket for {interaction.user}")
            await channel.send(f"{interaction.user.mention} has created an ticket!!!!")
            await interaction.response.send_message(f"I've open a ticket for you at {channel.mention}!", ephemeral= True)```
buoyant quail
#

if ticket is None: ticket.mention
how can it be, if it is None?

#

you want to change if and else i guess

slate swan
buoyant quail
slate swan
#

Oh

slate swan
buoyant quail
#

depends on what you want

#

If there are not channels, which channel id are you going to print?

slate swan
#

new error

#
@discord.ui.button(label = "Perchase!", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
    async def ticket(self, interaction: discord.Interaction, button: discord.ui.button):
        ticket = utils.get(interaction.guild.text_channels, name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
        if ticket is True: await interaction.response.send_message(f"you already have a ticket open at {ticket.mention}!!!", ephermeral = True)
        else: 
            overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
                interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files = True, embed_links = True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel=True, send_message = True, read_message_history=True)
            }
            channel = await interaction.guild.create_text_channel(name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}", overwrites= overwrites, reason=
            f"Ticket for {interaction.user}")
            await channel.send(f"{interaction.user.mention} has created an ticket!!!!")
            await interaction.response.send_message(f"I've open a ticket for you at {channel.mention}!", ephemeral= True)
            ```
#

I made if ticket is true

buoyant quail
slate swan
#

it works now thx

slate swan
#

I have a bug now lol

#

it lets me spam to make tickets with no errors

#

@buoyant quail

slate swan
#

Aye, why isnt my text being read?

I did !test Abān, im using unidecode so it should remove accents

     unidecode(ctx.message.content)
     if any(weak for weak in unidecode(ctx.message.content.split()) if weak in narrators.keys()):
        unidecode(ctx.message.content)
        keys = [weak for weak in unidecode(ctx.message.content.split()) if weak in narrators.keys()]

        found = ' '.join([str(elem) for elem in keys])

        weak = "weak"
        await ctx.send(found)
        await ctx.send("e")```

^ i get no response though with accents
#

if i do !test Aban, it sends

#

json

{"Aban": "weak", "test": "unknown"}

cloud dawn
#

Accents have different unicodes

#

I believe

#

!charinfo e

unkempt canyonBOT
cloud dawn
#

!charinfo ë

unkempt canyonBOT
cloud dawn
#

Yep

slate swan
#

Hm, so how would I go about translating it into a normal letter?

cloud dawn
#

!d unicodedata.normalize

unkempt canyonBOT
#

unicodedata.normalize(form, unistr)```
Return the normal form *form* for the Unicode string *unistr*. Valid values for *form* are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.

The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).
slate swan
#

NFC, NFKC?

cloud dawn
#

That's the form you want them in.

slate swan
#

Whats the normal form?

cloud dawn
#

"The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition."

#

!e ```py
import unicodedata

def strip_accents(s: str) -> str:
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')

print(strip_accents("Hëllo word!"))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello word!
slate swan
#

Cant find the unicodedata lib in my project interpreter to install?

cloud dawn
#

It's a default package.

cloud dawn
#

Maybe in the body.

young dagger
pliant gulch
#

Footers won't render

cloud dawn
#

Design flaw tbh

pliant gulch
#

But description should be fine iirc

#

There is also a timestamp field in the actual Embed

#

I think that'll work too

#

I cannot remember if fields work too but maybe

young dagger
pliant gulch
#

Well, yes

#

You never formatted the timestamp

pliant gulch
#

You cannot just send a raw timestamp

young dagger
pliant gulch
young dagger
#

So <t:datetime.datetime.now():R>

cloud dawn
#

!d discord.utils.format_dt

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...
slate swan
# cloud dawn It's a default package.

My code isnt reading messages with accents even though i normalised it?

  if any(weak for weak in unicodedata.normalize('NFKD', ctx.message.content.split()) if weak in narrators.keys()):
     keys = [weak for weak in unicodedata.normalize('NFKD', ctx.message.content.split()) if weak in narrators.keys()]

     found = ' '.join([str(elem) for elem in keys])

     weak = "weak"
     await ctx.send(found)
     await ctx.send("e")```

json

```{"Aban": "weak", "test": "unknown"}```
cloud dawn
slate swan
#

Damn

cloud dawn
#

Just call the function when comparing.

young dagger
#
    dt = datetime.now()
    end_time = datetime.timestamp(dt) + duration
    embed = discord.Embed(title=f'Giveaway: {prize}',
                          description=f'Ends: <t:{end_time}:R>',
                          color=discord.Color.green())
    message = await ctx.send(embed=embed)```
#

@pliant gulch @cloud dawn Any idea?

sick birch
#

also

#

!d discord.utils.format_dt

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

i would recommend using this instead

cloud dawn
sick birch
#

oh oop

#

Can't hurt to have a second opinion ¯_(ツ)_/¯

cloud dawn
#

Is it a second opinion if it's the same one?

sick birch
#

All the more reason to use format_dt

slate swan
#

I put an asterik in the test parms before ctx, yet my code cant read a json key with spaces?

        if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
            await ctx.send("e")
#

{"Aban b. Abi Ayyash": "weak"}

pliant gulch
#

ctx.message is always <prefix>test

#

Unless self is ctx???

#

The way the command signature is written makes it very confusing

slate swan
#

Hey

#

I need help

#

everytime I create a ticket it lets me create multiple tickets

#

and I am supposed to only have one

#

please help!

young dagger
sick birch
amber salmon
#

Im trying to make a ship command that saves the love percent
Code:
https://paste.pythondiscord.com/kiwapitohe
I keep getting this error i dont know how to fix it though im very lost

Traceback (most recent call last):
  File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\app.py", line 1163, in invoke_application_command
    await context.invoke()
  File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\context\base.py", line 326, in invoke
    await self.command.invoke(self)
  File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\commands\base.py", line 690, in invoke
    await self(context, **kwargs)
  File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\commands\base.py", line 605, in __call__
    return await self.callback(context, **kwargs)
  File "C:\Users\Lucaq\Novemeber Project\Bologne\bologne\extensions\ship.py", line 93, in echo
    insert_ship_doc()
  File "C:\Users\Lucaq\Novemeber Project\Bologne\bologne\extensions\ship.py", line 73, in insert_ship_doc
    collection.insert_one(ship_document)
  File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\pymongo\collection.py", line 3207, in __call__
    raise TypeError(
TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Database' object it is failing because no such method exists.

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

Traceback (most recent call last):
  File "C:\Users\Lucaq\Novemeber Project\Bologne\bologne\__main__.py", line 43, in errorHandler
    raise event.exception
lightbulb.errors.CommandInvocationError: An error occurred during command 'ship' invocation
slate swan
young dagger
# sick birch ```py discord.utils.format_dt(end_time, "R") ```

I tried it out but it still doesn't work:

    dt = datetime.now()
    end_time = int(discord.utils.format_dt(end_time, "R"))
    embed = discord.Embed(title=f'Giveaway: {prize}',
                          description=f'Ends: <t:{end_time}:R>',
                          color=discord.Color.green())
    message = await ctx.send(embed=embed)
sick birch
hushed galleon
young dagger
sick birch
#

yes

#

what units are duration in? Seconds?

young dagger
sick birch
#

You can probably just do

from datetime import datetime, timedelta
end_time = datetime.now() + timedelta(seconds=duration)
fmt_time = discord.utils.format_dt(end_time, "R")
embed = discord.Embed(..., description=f"... {fmt_time} ...")
#

@young dagger this

young dagger
sick birch
#

These are all your options

amber salmon
slate swan
young dagger
# sick birch From the docs <https://docs.python.org/3/library/datetime.html#timedelta-objects...

What do you think about this one?

duration_pattern = re.compile(r"(\d+)([smhd]?)")

@client.command()
async def create(ctx, duration: str, num_winners: int, *, prize: str):
    # extract the duration and the unit from the duration argument
    duration_match = duration_pattern.fullmatch(duration)
    if duration_match is None:
        return await ctx.send("Invalid duration format. Use `!create 2m`, `!create 1h`, `!create 1d`")
    duration_value, duration_unit = duration_match.groups()
    duration_value = int(duration_value)

    # convert the duration to seconds
    if duration_unit == "m":
        duration_in_seconds = duration_value * 60
    elif duration_unit == "h":
        duration_in_seconds = duration_value * 3600
    elif duration_unit == "d":
        duration_in_seconds = duration_value * 86400
    else:
        duration_in_seconds = duration_value

    # calculate the end time
    end_time = datetime.now() + timedelta(seconds=duration_in_seconds)
    fmt_time = discord.utils.format_dt(end_time, "R")
    embed = discord.Embed(title=f'Giveaway: {prize}',
                          description=f'Ends: Ends: {fmt_time}',
                          color=discord.Color.green())
    message = await ctx.send(embed=embed)```
sick birch
hushed galleon
slate swan
#

especially making the tables

sick birch
#

Everything seems hard till you try it 😄

hushed galleon
#

you can ask in #databases how to model your data, but in your case the simplest would be one table

#

with columns for guild_id, user_id, and channel_id

slate swan
#

(It should also be noted that an async library such as aiosqlite is more suitable for Discord bots than sqlite3, but the syntax, etc is almost identical)

hushed galleon
#

guild_id and user_id would be the unique identifier for someone's ticket channel, and if someone has a row in your table matching that then you know they created a ticket channel before, though not necessarily if that ticket channel still exists

hushed galleon
slate swan
#

True, it won't make much real difference in a lot of cases

hushed galleon
#

speaking of async wrappers, asqlite's pretty cool for this too, especially since it was written with discord bots in mind (and by the same maintainer of dpy)

(technically i cant say discord bots with evidence, but at least it optimizes sqlite for concurrency by default)

slate swan
#

asqlite enables wal mode by default, that's pretty nice

craggy sleet
#

this is so confusing as to why its not working

but i created a few buttons and dropdowns that give roles and it works for a little bit like normal but then it randomly starts responding with 'this interaction failed'?

#

they work perfectly fine until a certain point where they just fail

naive briar
#

Timed out, you restarted the bot but the views aren't persistent, ...

craggy sleet
#

how do you keep them persistent?

#

oh

#
super().__init__(timeout=None)

do you just put timeout=None and it should be good? in the button classes

hushed galleon
#

you also need each button to have a unique custom_id, and you'll need to re-add the persistent view whenever your bot restarts

slate swan
hushed galleon
#

^

craggy sleet
naive briar
#

!d discord.Client.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
craggy sleet
#

this is an example of what one of my buttons looks like

craggy sleet
naive briar
#

Subclass a view brainmon

slate swan
#

by "like that" i mean one defined inside a command, not any view that was initialised directly

craggy sleet
slate swan
#

not in on_ready, use setup_hook instead

#

on_ready can get triggered multiple times, which will make the code attempt adding the view again

naive briar
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
craggy sleet
#

oh okay i see

#

would this be something that looks correct?

slate swan
#

how could I fix this???