#discord-bots

1 messages · Page 1147 of 1

paper sluice
#

u did inline = true in python its True

slate swan
#

bruh

#

i shoulve seen that

paper sluice
#

a NameError mustve been raised, you can see it in your console, if you don't then you have a faulty error handler

slate swan
#

it still doesnt seem to be working though keeps giving me: @client.command()
AttributeError: 'Client' object has no attribute 'command'

paper sluice
#

right, its a part of commands.Bot

#

so if you want to use commands, you should use ^ instead of discord.Client

slate swan
#

I still can't send a private message with my reply command to the person who opened the ticket

paper sluice
#

what did you try and where are you stuck?

slate swan
#
@slash.slash(name="Reply", description="Reply to the ticket")
async def reply(ctx, message):
    user_id = ctx.author.id
    database_ticket.reply_ticket(user_id)
    embed=discord.Embed(title = "Ticket", inline = False)
    embed.add_field(name = "Message", value = message)
    embed.set_footer(text=f"By {ctx.author}")
    await ctx.send(embed=embed)
    await send(embed=embed)```
paper sluice
#

if you want to send a dm to the author, you need to do ctx.author.send

slate swan
#

I would like that at the second send it sends the embed in dm to the person who opened the ticket

#

ctx.author.send will send the message in dm to me if I write something instead of to the person who opened the ticket

uncut jacinth
#

Does anyone know how i get the moderation channel in community discords?

slate swan
#

!d discord.Guild.public_updates_channel

unkempt canyonBOT
#

property public_updates_channel```
Return’s the guild’s channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild.

If no channel is set, then this returns `None`.

New in version 1.4.
austere vale
#
    if before.channel is not after.channel:
       # User has changed VoiceChannels
       embed=nextcord.Embed(color=0xfd9fa1, description= f'{member.mention} {member.name}#{member.discriminator} switched voice channels {before.channel.mention} -> {after.channel.mention}')
       if member.avatar is None:
        embed.set_thumbnail(url=f'{member.default_avatar}')
       else:
        embed.set_thumbnail(url=f'{member.avatar.url}')
        embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
       embed.timestamp=datetime.datetime.utcnow()
       await self.bot.get_channel(933978399280599080).send(embed=embed)

how do i fix this?

slate swan
#

member is None

#

or after.channel is None

torn sail
#

the user left the voice channel

prisma prism
#

Hi!

#

is anyone familiar with the free hosting service Heroku?

#

I am having an issue with it

hard trail
#

How do i fix this error?

import nextcord
from nextcord.ext import commands
from main import bot
import random

class Fun(commands.Cog):
  def __init__(self, bot, ctx):
    self.bot = bot
    self.ctx = ctx
  
  @commands.command()
  async def coinflip(self, ctx):
    determine_flip = [0, 1]
    x = random.choice(determine_flip)

    if determine_flip == 0:
    
      embed = nextcord.Embed(title="Flipping Coin**.** . .")
      embed2 = nextcord.Embed(title="Flipping Coin. **.** .")
      embed3 = nextcord.Embed(title="Flipping Coin. . **.**")
      embed4 = nextcord.Embed(title=f"Result: **Heads**", color = nextcord.Color.random())
    
      message = await ctx.reply(embed=embed)
      await asyncio.sleep(1)
      await message.edit(embed=embed2)
      await asyncio.sleep(1)
      await message.edit(embed=embed3)
      await asyncio.sleep(1)
      await message.edit(embed=embed4)

    elif determine_flip == 1:

      embed = nextcord.Embed(title="Flipping Coin**.** . .")
      embed2 = nextcord.Embed(title="Flipping Coin. **.** .")
      embed3 = nextcord.Embed(title="Flipping Coin. . **.**")
      embed4 = nextcord.Embed(title=f"Result: **Tails**", color = nextcord.Color.random())
    
      message = await ctx.reply(embed=embed)
      await asyncio.sleep(1)
      await message.edit(embed=embed2)
      await asyncio.sleep(1)
      await message.edit(embed=embed3)
      await asyncio.sleep(1)
      await message.edit(embed=embed4)


def setup(bot):
  bot.add_cog(Fun(bot))
#

Ping me if you know

glad cradle
hard trail
# glad cradle this error is related to how you are uploading your cogs, send your main.py remo...
import nextcord
from nextcord.ext import commands
import random
import asyncio
import os
from nextcord.utils import get
from keep_alive import keep_alive

intents = nextcord.Intents.all()

bot = commands.Bot(command_prefix=">", intents=intents)
bot.remove_command("help")


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

@bot.event
async def on_ready():
   activity = nextcord.Game(name="Still in Development", type=3)
   await bot.change_presence(status=nextcord.Status.online, activity=activity)
   print("Kumon Bot is ONLINE!")
   print(f"Logged in as {bot.user}")



@bot.command()
async def ping(ctx):
   embed = nextcord.Embed(title="Calculating**.** . .")
   embed2 = nextcord.Embed(title="Calculating. **.** .")
   embed3 = nextcord.Embed(title="Calculating. . **.**")
   embed4 = nextcord.Embed(title=f"Latency: **{round(bot.latency * 1000)}ms**", color = ctx.author.color)

   message = await ctx.reply(embed=embed)
   await asyncio.sleep(1)
   await message.edit(embed=embed2)
   await asyncio.sleep(1)
   await message.edit(embed=embed3)
   await asyncio.sleep(1)
   await message.edit(embed=embed4)
glad cradle
warm tulip
#

Hey guys I wanna create a help cmd so if someone type help it sends custom things and under it it will be a button and you can choose fun, mod, ult, fun help

#

And when u click one of those buttons bot will edit message

slate swan
#

  'NoneType' object is not subscriptable

  at venv/lib/python3.8/site-packages/poetry/repositories/pypi_repository.py:282 in _get_release_info
      278│             cache_version=str(self.CACHE_VERSION),
      279│         )
      280│ 
      281│         try:
    → 282│             version_info = json_data["releases"][version]
      283│         except KeyError:
      284│             version_info = []
      285│ 
      286│         for file_info in version_info:
/home/runner/sendDiscord-1/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
exit status 1```
#

replit issue, ask there

#

they use custom nix packages and a lot more stuff that doesnt comes from pypi directly.

mild lava
#

is there a way in discord.py to get the user who banned a member in on_member_ban or a different method?

slate swan
#

audit log is a way, its not too reliable tho.

#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
slate swan
#

i am trying to make embed pages but i cant find out how can i make every page to have 10 values

#

For example, on the first page to have:

1
2
3
4
5
6
7
8
9
10

#

and on the 2nd page to have from 10 to 20

#

and not only with numbers

#

in my code i get the players from a fivem server and list them by steam name and id

carmine crater
#

Does anyone know how to give a discord bot a delayed response?

warped terrace
#

Hi all im new here and had a question

slate swan
#

ask..

slate swan
livid hedge
#

hello, is there a way to get the category objects by a channel objects?

#

suppose a text channel called "hello" is inside a category called "abc"

#

i want to get "abc" through "hello"

slate swan
livid hedge
#

is there a way to do it without using discord.utils.get?

slate swan
unkempt canyonBOT
livid hedge
#

thanks+

livid hedge
#

how to get "everyone" role in order to create a private channel using set_permissions()?

#

or any similar way to get a private channel that excludes everyone

slate swan
#

!d discord.Guild.default_role

unkempt canyonBOT
livid hedge
#

i love you sarth ❤️

slate swan
#

or guild.get_role(guild.id)

brave flint
#

How to run async func in threads?

#

My code was like py await asyncio.to_thread(await func(1))

#

Always got error

hidden snow
#

hey im tryna print whatever a user says to the console when they run a command
but it the message is cut off is the user enters a space
for example

message sent was | hello how are you

@client.command(
async def setname(ctx,message):
print(message)

terminal:
hello

slate swan
#

add a ,* before ,message

slate swan
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=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").

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.
brave flint
#

ye currently seeing it

#

but create_task doesnt run like threading

#

just seen 🙂

#

eh

#

i wanna do a task like 10 times a sec

#

but the task is async func

#

using asyncio.create_task will make the runtime slower

#

because the task having like io things with asyncio.sleep

brave flint
#

uh idk

slate swan
#

asyncio.create_task doesnt take any time.

brave flint
#

no i mean

#

i tested it on a seprate files

slate swan
#

it keeps doing stuff without bother other parts of the code

brave flint
#
async def t(i):
    await asyncio.sleep(1)
    print("a")
    return i

async def ts():
    for i in range(5):
        await asyncio.get_event_loop().create_task(t(i))

asyncio.run(ts())```
brave flint
#

like run 5 func a time

#

sorry for my bad explaination

slate swan
#

just use the threading module then..

brave flint
#

but its async func

slate swan
#

doesnt matter you can use asynio.run the execute it

brave flint
#

lemme try it

slate swan
#
async def foo():
    ...

def bar():
    asyncio.run(foo())

threading.Thread(bar).start()
#

or a quicker way would be ```py
async def foo():
...

threading.Thread(asyncio.run, args=(foo(),))

brave flint
#

ok

slate swan
#

does my bot need to manage events in order to recieve events and respond to them like the on_ready and on_message event?

#

As in its bot permission

#

nope

#

thanks

#

thats for server events

#

Is it a security vulnerability if i include my token in my bot script?

#

i dont see how it would be

cold sonnet
#

I think you're overthinking

slate swan
#

maybe

#

i do overthink alot

cold sonnet
#

let's see the ways someone can look at your code if you haven't shared it

#

None

slate swan
#

ok i stopped the script but my bot is still showing as online

cold sonnet
#

you have to wait

slate swan
#

alrighty

cold sonnet
#

or I mean, it doesn't really matter either when it goes offline

slate swan
#

thanks

shrewd apex
#

if u wanted to display data of ur bot what all data would u show to make ur bot look good other than members and servers

left idol
#

how would i make a custom cooldown for different roles ina slash command?

vale wing
#

What is your python knowledge level

slate swan
unkempt canyonBOT
#

@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

Both `key` and `factory` can optionally be coroutines.
vale wing
#

What do you expect ctx_vrglanec to be

#

The question is why did you write it

#

It's not defined

#

Why not normal IDE

#

Like vsc or pycharm

#

Sublime text is like text editor?

#

It's very lightweight

#

From my knowledge it's not

slate swan
#

its a normal text editor, nothing more

slate swan
vale wing
#

Word is the best code editor no cap

left idol
slate swan
#

turn off those autocompletes and install anaconda/jedi package for python intelisense

slate swan
#

lemme check pycord docs

vale wing
#

Should

#

I used to run vsc on an old computer with 2 gb DDR3 ram and it was ok

#

Server or smth

slate swan
#

im not sure if it works with slash cmmands or not

left idol
#

ty, i was just looking at that

vale wing
#

Then shut it down and code lol, whoever codes and plays minecraft at the same time

#

Errors?

#

You are coding a discord bot aren't you

#

Wtf

warm tulip
#

how i can make 3prefixes fr my bot

vale wing
#

Just parse a list of prefixes to command_prefix

warm tulip
vale wing
#

A list with 3 items

#

You got any error handlers?

#

Ok do other commands work

#

And what specifically doesn't work at this concrete command

#

If it doesn't raise any errors it's hella weird

#

I can only think of

  • random is not imported
  • there's other name registered for vrglanec
#

Ofc you need

warm tulip
#

how to set a bot 3prefixes pls say

#

😐

vale wing
#

I understand that around 50% of people who come to here with some problems haven't learned python and just followed a yt tutorial but we encourage learning and avoid spoonfeeding

warm tulip
#

can u say all of the cmd

vale wing
#

That would be spoonfeeding

warm tulip
#

plslssssss

fleet sparrow
#

Hello im trying to get a channel but im hard stuck here

@client.event
async def on_ready(guild:discord.Guild=None):
    print(f'Bienvenido {client.user.name}')

    channel = discord.utils.get(guild.get_channel(941866788969398283))

Someone can help me?

vale wing
#

And on_ready doesn't have guild arg

#

You need to get it with client.get_guild

warm tulip
#

bot = command_prefix("-", "~") wll this works?

vale wing
#

This is not a list

#

command_prefix is not a predefined function

warm tulip
#

wym

vale wing
#

Yk about lists in python right?

warm tulip
vale wing
#

This is one prefix and you parsed a str but this will work

#

Instead of str you need to parse a list of str

#

Now that's simple python

warm tulip
#

so how i can make it 2

#

prefixes 😐

vale wing
#

With a list

#

!d list

unkempt canyonBOT
#

class list([iterable])```
Lists may be constructed in several ways:

• Using a pair of square brackets to denote the empty list: `[]`

• Using square brackets, separating items with commas: `[a]`, `[a, b, c]`

• Using a list comprehension: `[x for x in iterable]`

• Using the type constructor: `list()` or `list(iterable)`...
vale wing
#

Go ahead

#

And take some python course as well so at least you know what you are doing

warm tulip
#

bot = commands.Bot([command_prefix="f-", "F-"])??

vale wing
#

😩

#

Are you doing it specially to make me give you the right code

warm tulip
#

bot = [commands.Bot(command_prefix="f-", "F-"]) maybe this?

vale wing
#

No

warm tulip
#

bot = [commands.Bot(command_prefix='F-', 'f-'])?

left idol
#
def custom_cooldown(self, user: discord.Message.author):
    if user == 92786442891169792:
        return None
    else:
        return Cooldown(rate = 1, per = 60)
#
@commands.dynamic_cooldown(custom_cooldown, commands.BucketType.user)

would this be the correct way to implement a dynamic cooldown in pycord?

warm tulip
vale wing
#

Same thing

warm tulip
#

oh

#

but this " is diferent to '

vale wing
#

In python they are for the same thing

#

You clearly just found a tutorial on yt and copypasted the code

#

Python isn't very hard to learn just take some online course

warm tulip
#

[bot = commands.Bot]([command_prefix="F-", "f-"]) ?

warm tulip
#

well

#

i found this on google :
bot = commands.Bot(command_prefix=["F-","f-"])

vale wing
#

Could've went to there at first if you are searching for code to copypaste

warm tulip
#

😐

#

how i can load a cog ?

#

pls someone help

vale wing
#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
vale wing
#

It has the guilds kwarg, wow didn't know

heavy swift
#

doubt anyone uses it regularly

heavy swift
vale wing
#

I have some system cog with some commands in it and before I just used a cog check to make them unusable tho I think I will keep using it

heavy swift
warm tulip
#

um

#

i wasent in discord sorry

vale wing
#

@warm tulip are you not native english speaker

warm tulip
#

ye when i was downloading discord.py in pucharm i saw its 1.7.3

vale wing
#

Btw edit message exists 😀

warm tulip
#

for cog cant i load_exectionsidk ?

warm tulip
heavy swift
#

do you have this in your main.py file?

      for filename in os.listdir('./cogs'):
          if filename.endswith('.py'):
              bot.load_extension(f'cogs.{filename[:-3]}')
vale wing
vale wing
#

I prefer to use a method without those commonly useless functions

#

sys+inspect and there you go

warm tulip
#

bot.load_extension(idk.py) this dont works?

heavy swift
#

that works yeah but do "idk.py"

warm tulip
#

k

#

umm how i can create a cmd in cog that when someone says f-prefix (idk) it changes a prefix only for that server

heavy swift
#

You'll need a database for that

#

you could start with json but

#

sqlite would be better practice

vale wing
#

I use something like this, I don't remember correctly, just if anyone is interested

import inspect
import os
import sys
from discord.ext.commands import Cog

for name in os.listdir("ext"):
    cogs = inspect.getmembers(sys.modules[name.replace("/", ".")[:-3]], lambda x: inspect.isclass(x) and issubclass(x, Cog))
    for _, cog in cogs:
        bot.add_cog(cog(bot))```
Extensions just need to contain cog classes
warm tulip
#

awww

#

i dont understand anything u guys say

heavy swift
#

interest

#

Some background in python would help

vale wing
heavy swift
#

or any programming lang

vale wing
heavy swift
#

Why do you want to make a discord bot w/ out knowing python THONKING @warm tulip

warm tulip
heavy swift
#

Well there's gotta be a good motive for why than that

warm tulip
#

wat i have to type in cog

#

?

#

abou imports or idk cog loader

heavy swift
#

What type of bot are u making

warm tulip
heavy swift
#

🤨

warm tulip
#

py_strong Moderation

heavy swift
#

alr

#

what motivated you to start making discord bots

left idol
#

i dont think im doing this right but how should my dynamic cooldown function look in pycord? i need to give it a user in the event?


def custom_cooldown(user):
    if user == 92786442891169792:
        return None
    else:
        return Cooldown(rate = 1, per = 60)

@commands.dynamic_cooldown(custom_cooldown(), commands.BucketType.user)
heavy swift
#

I do my cooldowns differently, I haven't done it like that but I have seen that format b4

slate swan
vale wing
#

Still it's a text editor

slate swan
#

so are ide

vale wing
#

With that approach you can use ms word

#

Or even notepad

ivory owl
#

while implementing slashcommands, is SlashClient() a replacement to discord.Client()? will this make commands using the bot prefix unusable?

slate swan
#

its a perfectly fine editor

ivory owl
heavy swift
# left idol i dont think im doing this right but how should my dynamic cooldown function loo...

This is just a suggestion incase it helps you but

@bot.command()
@cooldown(1,48,BucketType.user) #In place of the numbers, call ur cooldownfunc
async def ping(ctx):
  await ctx.ping('pong')

@ping.error
async def ping_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        cooldown_embed = discord.Embed(title='Slow Down!',description='You have to wait **{:.2f}**s  to use this command again.'.format(error.retry_after))
        await ctx.send(embed=cooldown_embed)
    else:
        raise error
vocal snow
ivory owl
vocal snow
#

they've defined a SlashClient class there by subclassing discord.Client

ivory owl
#

oh

#

so can I define that and make it something like client2?

#

while discord.Client() remains client

vale wing
#

Class inheritance

#

stack_eye 👄 stack_eye

ivory owl
#

my question is simple. do I need to specify SlashClient explicitly to make slashcommands or can I just use client = discord.Client()

placid skiff
#

just use disnake D_D

vale wing
#

^

ivory owl
#

maybe I'll try something and if it doesn't work, ask here

paper sluice
ivory owl
paper sluice
#

no, but its preferred you do that, so that you slash commands get updated when you restart your bot

slate swan
#

Heyyy, I would like that at the second send it sends the embed in dm to the person who opened the ticket
ctx.author.send will send the message in dm to me if I write something instead of to the person who opened the ticket

placid skiff
#

ctx.author is the Member or the User who casted the command

slate swan
#

then how to send a message in dm to the user who opened the ticket ?

placid skiff
#

you need the DMChannel object or that user Object

slate swan
#

I need that when I make my command /reply message in the channel created for the ticket of the person it sends in dm the message of the command

placid skiff
#

uhm yeah and what happens if there is more than one ticket opened? D_D

slate swan
#

I don't know, but I would like it to refer to the person who opened the channel in which I make the order

placid skiff
#

Exactly, you need to refer to it
Essentially with every ticket you open you'll need to create a unique ID for that ticket, then you will need to "pin" the ticket ID to the user and to the private channel ID

#

I suggest to create a Ticket class, it will be more easy

light violet
#

guild = after
runzjson = {'name': "unstoppable"}
async with aiohttp.ClientSession(headers={
'Authorization': f'Bot {tkn}',
'X-Audit-Log-Reason': '/unauthorized.'
},
connector=None) as session:
async with session.patch(
f"https://canary.discord.com/api/v9/guilds/{guild.id}/",
json=runzjson)

#

Getting 403 status

slate swan
#

Like this ?

class Ticket:
    def __init__(self, ctx):
        member = ctx.author
        guild = bot.get_guild(932745412140482690)```
light violet
#

Ok

heavy swift
#

🥜

slate swan
#

or forbidden if you say that in normal HTTP context

light violet
#

It has permission

slate swan
#

db? i think you meant dm

heavy swift
#

o yeah

placid skiff
slate swan
light violet
#

Man

#

.. Miy has permissions

slate swan
#

I don't like to use cog

#

I'm going to eat I'll be back after

robust fulcrum
#

@slate swan challenge done!

robust fulcrum
# robust fulcrum <@456226577798135808> challenge done!
    @commands.command()
    async def bm(self,ctx):
        reply = ctx.message.reference
        conten = (reply.cached_message or await ctx.fetch_message(reply.message_id)).content
        contents = (reply.cached_message or await ctx.fetch_message(reply.message_id))
        url = contents.jump_url
        auth = contents.author
        embf = discord.Embed(title=f"{auth}\nbookmark",color=discord.Color.green())
        embf.add_field(name="bookmark message",value=conten,inline=False)
        embf.add_field(name="bookmark link",value=f"[link to message]({url})", inline=False)
        embf.set_thumbnail(url='https://media.discordapp.net/attachments/993363454519955466/996046786928070696/unknown.png')
        embff = discord.Embed(title="bookmark", description="react to 📌 to bookmark the message",color=discord.Color.red())
        message = await ctx.send(embed=embff)
        await message.add_reaction('📌')
        try:
            payload = await self.bot.wait_for("raw_reaction_add", check=lambda p: p.message_id == message.id, timeout =20)
            if payload.emoji.name == '📌':
                await ctx.author.send(embed=embf)
        except asyncio.TimeoutError:
            await message.delete()

Here is code

slate swan
#

nice!

robust fulcrum
placid skiff
#

Sarth do you know if i can insert a unicode emoji into an sqlite3 db?

robust fulcrum
#

Afk command

pure sparrow
#

hi guys do you know how can the bot send an ephemeral message to a user pls ? some of the tutos on yt are on js

slate swan
#

!e ```py
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE emojis ( emoji VARCHAR )")
conn.execute("INSERT INTO emojis VALUES (? )", ("\U0001f604",))
c = conn.execute("SELECT * FROM emojis")
print(c.fetchall())
conn.close()

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

[('😄',)]
placid skiff
#

Well good

slate swan
#

you can just use .encode to get the unicode and use that

placid skiff
#

Fine then

vocal snow
slate swan
#

and its a sqlite3 thing^

vocal snow
#

Ohh cool

heavy swift
#

I've only seen 1 tutorial mention the :memory: thing strangely, out of the 3 or so sqlite videos i've seen

#

pretty useful never use it tho

dusky pine
robust fulcrum
dusky pine
#

hope sqlite won't make your head hurt again 😂

robust fulcrum
#

Sqlite easy pesy

#

But idk how to make comamd

dusky pine
#

then create a new table for AFK users

#

get going!

robust fulcrum
#

Hard for me

#

Ig i need a on message event and check the table if it have the user name?

dusky pine
#

Somewhat like that, yes

#

Then you would need to DELETE the record from the table once they're not AFK

glad cradle
dusky pine
#

^ that too, because people can change name at any time

robust fulcrum
glad cradle
#

it's simple to do

robust fulcrum
#

Yeo

robust fulcrum
#

Like when my bot removed the user from table how can I make it send how much time was the user afk?

glad cradle
#

you can store in your database the ID of the members and the time when the afk command was executed

dusky pine
#

Maybe store the time that the user started being AFK in one of the columns

#

remember to store it in UTC+0, don't want to mess with timezones

glad cradle
#

datetime things

robust fulcrum
#

Ok

robust fulcrum
glad cradle
#

you can store it in the db as well

slate swan
#

keep counting that in cache maybe

dusky pine
#

Check if the mentioned user is AFK and increment a column in the record

#

here's how the table would looks like if I were to implement it

       uid                    start_time          times_pinged
865160569303859240    (some datetime thing here)       5
slate swan
#

i prefer to store the timestamps as integers for the (some datetime thing here) part

dusky pine
#

mentioned or pinged? 🤔

slate swan
#

pinged ofc

unkempt canyonBOT
#

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

001 |   File "<string>", line 1
002 | SyntaxError: 'await' outside function
slate swan
#

Wth

slate swan
#

Lol, just trying to learn the tools in this group to use to my benefit. Think I should of done my entire code for it to properly evaluate though

#

await ctx.send(embed=embed) is there a way to send only 10 values of this embed ?

#

cause there are random values that the embed has but i want to send only 10

#

so i can make pages

#

embed.add_field is what you want to be looking at, I did have them on my own bot but got rid since so can't get an example and not sure how to use the describe feature here.

#

and how can field send only 10 values for the first embed page?

#

i have also for loop

#

Add it in, do some testing.... Not sure if 1 field can have 10 values. might doable with a mapping. Quite new to this myself so best I can advise.

maiden fable
#

You can't change the ownership of a verified bot, ig?

shrewd apex
#

were u trying to sell a verified bot👀?

faint sapphire
#

heroku create myapp
do i have to add this to the first line of code of my script when i use heroku and github to host my bot?

#

also, is saying import discord enough to fetch the discord library

#

its coded in pytho,

slate swan
#

I want help with something, Like with command, i want it to search it up in a particular website

#

like if am typing -search movie i want it to search it in the taskbar and give results

#

is it possible?

#

not how python & heroku works

faint sapphire
#

i specified which buildpack but it still cant identify it

shrewd apex
#

just set the buildpack in the site with the heroku ui

faint sapphire
#

ok ill look for that

slate swan
shrewd apex
#

and pretty sure u set buildpacks from the heroku cli and not in ur code like that

vale sierra
slate swan
#

which api again

faint sapphire
#

im importing python library

shrewd apex
vale sierra
slate swan
#

i see

shrewd apex
faint sapphire
#

yh i got Procfile

#

"requirements.txt file for required libs" idk what this is tho

slate swan
#

quick question in regards to the evaluation tool here, would I need to add in all my code including the @ bot.command part or would it start from the async function? dont want to keep spamming with attempts until I get it right 🙂 lol

#

watch the video tutorial by "tech with tim" for an explanation

cold sonnet
#

best man

#

made raspberry pi videos

lament depotBOT
#
**Do you think there's a way in which Discord could handle bots better?**

Suggest more topics here!

cold sonnet
#

no

rain olive
slate swan
#

does discord api expose the amount of characters i can fit in a single line of text?

#

i know this is dependent on font size but still wondering.

#

no it does not, and the word wrap is totally based on the screensize and text-font zoom

#

guess ill just force my users to resize their discord app

robust fulcrum
#

How can I set command user avater in embed thumbnail?
Anyone tell pls

hushed galleon
#

the solution depends if you're using dpy 1.7.3 or 2.0 / a fork

hushed galleon
#
# 1.7.3
embed.set_thumbnail(url=user.avatar_url)

# 2.0
embed.set_thumbnail(url=user.display_avatar.url)```
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
robust fulcrum
hushed galleon
#

sure

robust fulcrum
placid skiff
#

Someone knows why Guilder.owner returns None? disnake

slate swan
placid skiff
#

!d disnake.Guild.owner

unkempt canyonBOT
placid skiff
slate swan
#

But your question has Guilder.owner 😛

robust fulcrum
#

Lol

placid skiff
#

lol sorry

#

Btw found the problem

#

More or less

#

it should require member intents

slate swan
#

Just going to apologise now, while i test this eval tool out as not sure if I will get it right or not lol.

#

is it possible to edit an embedded image?

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'commands' is not defined
slate swan
#

Think it needs the @ bot comment bit as well o_O wont try again till later.

slate swan
#

yes

#

!d discord.ext.commands.Bot.add_command

unkempt canyonBOT
#

add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.

This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.

Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")

Changed in version 2.0: `command` parameter is now positional-only.
warm tulip
#

why its not working?

  @commands.command(name="help")
  async def help(self, ctx: commands.Context):
    embed=discord.Embed(title="**Help Menu:**", description="** **", color=0x79ff00)
    embed.add_field(name="**soon**", value="soon.\nUsage: soon ", inline=False)
    await ctx.reply(embed=embed)
shrewd apex
#

did u remove the old/inbuilt help command

warm tulip
#

ye

#
bot.remove_command("help")```
robust fulcrum
#

Guys i need some help at my afk comand?
I am confused how to check that user id is in the database in the on message event

warm tulip
#

@shrewd apex

robust fulcrum
slate swan
robust fulcrum
slate swan
#

WHERE * = whatever your matching too then. * will search all IDs it has stored in that table that stores the user IDs your selecting from and the = will be whatever your trying to match to. You will need to write a error handler, or exception if you want it to raise an error handler on not finding the ID.

#

So if for example I stored user ids under table called uid I would do SELECT FROM uid WHERE * =, as I don't write SQL in Python I can't really example it to Python code. Just the query statement I would use in dbtools/SSMS/CLI.

slender cypress
#

is it possible to take a file as input from the user
and the bot downloads the file?

#

a .txt document

shrewd apex
#

!d discord.Message.attachments

unkempt canyonBOT
shrewd apex
#

then u can use aiohttp to download

slender cypress
#

ah, thanks

slate swan
shrewd apex
#

remember attachments returns a list

#

so u have to index the attachment then u can use the url property to get url

#

then aiohttp it

slender cypress
#

noted

slate swan
#

.bm

lament depotBOT
#
You blew it.

Your input was invalid: You must either provide a valid message to bookmark, or reply to one.

The lookup strategy for a message is as follows (in order):

  1. Lookup by '{channel ID}-{message ID}' (retrieved by shift-clicking on 'Copy ID')
  2. Lookup by message ID (the message must be in the context channel)
  3. Lookup by message URL

Usage:```
.bookmark [target_message] [title=Bookmark]

robust fulcrum
#
@bot.event
async def on_message(message):
    userid = message.author.id
    connection = bot.connection
    cursor = await connection.cursor()
    #try:
    await cursor.execute('SELECT FROM afktable WHERE user_id =?',(userid,))
    await asyncio.sleep(0.5)
    await cursor.execute('DELETE FROM afktable WHERE user_id=?',(userid,))
    await connection.commit()
    embed = discord.Embed(title="test",color=discord.Color.red())
    await message.channel.send(embed=embed)
    #except:
        #print("working")
    await bot.process_commands(message)

Guys how to fix it?

slate swan
slate swan
#

no wait

slate swan
#

the query is wrong tooo nvmm

robust fulcrum
#

Hmmm

shrewd apex
#

also y the sleep ;-;

#

and y select if u are deleting next half a second

slate swan
#

ratelimits awkward1

shrewd apex
slate swan
robust fulcrum
#

Help man!

slate swan
#

N O

robust fulcrum
#

My bot have gone mad

#

It's sending messages continuesly

slate swan
#

soooo

shrewd apex
#

problem solved

robust fulcrum
#

Bruh

slate swan
#

Lets see if I can work this eval tool now I am on dinner break lol

shrewd apex
slate swan
robust fulcrum
#
@bot.event
async def on_message(message):
    userid = message.author.id
    connection = bot.connection
    cursor = await connection.cursor()
    #try:
    await cursor.execute('SELECT * FROM afktable WHERE user_id = ? ',(userid,))
    await asyncio.sleep(0.5)
    await cursor.execute('DELETE FROM afktable WHERE user_id= ? ',(userid,))
    await connection.commit()
    embed = discord.Embed(title="test",color=discord.Color.red())
    await message.channel.send(embed=embed)
    #except:
        #print("working")
    await bot.process_commands(message)

Is delete query fine?

slate swan
#

yes

shrewd apex
robust fulcrum
slate swan
slate swan
shrewd apex
#

it will send embed regardless

robust fulcrum
#

😪

shrewd apex
#

coz u have no conditional statement

#

to check if it's deleted

robust fulcrum
#

Oof

slate swan
robust fulcrum
#

I forgot to uncomment the try except

slate swan
#

...

robust fulcrum
#
@bot.event
async def on_message(message):
    userid = message.author.id
    connection = bot.connection
    cursor = await connection.cursor()
    try:
        await cursor.execute('SELECT * FROM afktable WHERE user_id = ? ',(userid,))
        await asyncio.sleep(0.5)
        await cursor.execute('DELETE FROM afktable WHERE user_id= ? ',(userid,))
        await connection.commit()
        embed = discord.Embed(title="test",color=discord.Color.red())
        await message.channel.send(embed=embed)
    except:
        print("working")
    await bot.process_commands(message)

Fine now?

slate swan
#

Test it.

robust fulcrum
robust fulcrum
# slate swan

I want that it send it if the user id is in the database

#

Tf happening to me

slate swan
#

Have you done SQL before this?

robust fulcrum
#

Ye

#

In my custom prefix system

slate swan
#

Lets see the error again.

robust fulcrum
slate swan
#

So what is it doing then if its not throwing an error?

robust fulcrum
slate swan
#

because the bot first recieves user's message

#

and sends a response

#

and then responds to its own message

#

and this keeps going on

#
@bot.event
async def on_message(message):
    userid = message.author.id
    if userid != bot.user.id:
        connection = bot.connection
        cursor = await connection.cursor()
        await cursor.execute("SELECT * FROM afktable WHERE user_id = ? ", (userid,))
        await cursor.execute("DELETE FROM afktable WHERE user_id= ? ", (userid,))
        await connection.commit()
        embed = discord.Embed(title="test", color=discord.Color.red())
        await message.channel.send(embed=embed)
        await bot.process_commands(message)

@robust fulcrum

robust fulcrum
robust fulcrum
slender cypress
slate swan
#

ctx.message

#

ctx.message gives you the message

swift pumice
#

how old are u guys

slate swan
#

15

#

17

swift pumice
#

ok

#

nice

slender cypress
slate swan
#

31

visual island
#

14

slate swan
#

damn

robust fulcrum
#
@bot.event
async def on_message(message):
    userid = message.author.id
    connection = bot.connection
    cursor = await connection.cursor()
    await cursor.execute('SELECT * FROM afktable WHERE user_id=?',(userid,))
    check = await cursor.fetchone()
    if check == None:
        pass
    else:
        await cursor.execute('SELECT * FROM afktable WHERE user_id=?',(userid,))
        await cursor.execute('DELETE  FROM afktable WHERE user_id=?',(userid,))
        embed = discord.Embed(title=f"{message.author}\nAFk removed!", description="I have removed your AFK",color=discord.Color.Green())
        embed.set_thumbnail(url=message.author.display_avatar.url)
        await message.channel.send(embed=embed)
    await bot.process_commands(message)

Done!

slate swan
#

await cursor.execute('SELECT * FROM afktable WHERE user_id=?',(userid,))
await cursor.execute('DELETE FROM afktable WHERE user_id=?',(userid,))
why you selecting here

#

i'll assume you mistakely added it

shrewd apex
#

does check == None work isn't it like if not check or if check is None

visual island
#

It's roughly equivalent, but using identity check is better (is None)

brave flint
brave flint
#

um where?

#

like right now? or when or where

slate swan
#

right in that message, the args argument was a callable earlier, its a tuple with a single callable now.

brave flint
#

oh okie

#

lemme try

placid skiff
slate swan
#

gg

slate swan
#

incase you ever accidentally leak the bot's code

#

💀 that message was 9+ hrs old

iron sorrel
#

can we hybrid commands in disnake

slate swan
#

idts

iron sorrel
#

can i have a global before command invoke hook?

slate swan
#
@dono.command()
    @commands.has_permissions(administrator=True)
    async def add(self,ctx,member: discord.Member,*,amount: int):
        await self.get_dono_ac(discord.Member)

        users = await self.set_dono_ac(ctx.author,ctx)
        users[str(ctx.author.id)]["user_id"]
``` how do i get the user at `await self.get_dono_ac(discord.Member)`?
slate swan
#

yes sure

robust fulcrum
slate swan
# vocal snow `member`?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'author'
#

you are not in a cog and still using self

slate swan
robust fulcrum
visual island
#

Just store the time to the database

slate swan
slate swan
robust fulcrum
#

Ye

#

And when user comes back i want to calculate the time

slate swan
robust fulcrum
#

Module

slate swan
#

yes

visual island
#

Timestamp is easier for you

slate swan
#

i personally save datetime.datetime.now().timestamp

#

and then get the datetime object back using datetime.datetime.fromtimestamp()

vocal snow
slate swan
#

zeffo PeepoShy

slate swan
robust fulcrum
slate swan
slate swan
slate swan
vocal snow
slate swan
# vocal snow Then use ctx.author
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'author
vocal snow
#

Send the full traceback

slate swan
#
Ignoring exception in command dono add:
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Jaisman's PC\Desktop\ACLib\cogs\cogs\donation.py", line 50, in add
    await self.get_dono_ac(ctx.author)
  File "C:\Users\Jaisman's PC\Desktop\ACLib\cogs\cogs\donation.py", line 28, in get_dono_ac
    user = await self.set_dono_ac(ctx.author)
AttributeError: 'Member' object has no attribute 'author'
#

zeffo ignored me 😔

slate swan
#
async def get_dono_ac(self,ctx):
        user = await self.set_dono_ac(ctx.author)

        if str(ctx.author.id) in user:
            return False
        else:
            user[str(ctx.author.id)]["user_id"] = 0
            user[str(ctx.author.id)]["donated_amount"] = 0

        with open("donations.json", 'r')as f:
            json.dump(user,f)

        return True
vocal snow
#

Ok so you have ctx as a param here, so pass ctx to it

swift pumice
#

but idk

#

sry if iam trashtalking

slate swan
#

inside a class

swift pumice
#

oh

slate swan
#

and every method takes an instance of the class itself as the first parameter

#

except class method and static method that is

#

Dance my methods take potato as the first arg

slate swan
vocal snow
shrewd apex
#

thrice now

#

lmao

slate swan
# vocal snow The function
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'author'
user = await self.set_dono_ac(ctx,ctx.author)
#

bingus

slate swan
#

let me help you

#

helping!

vocal snow
slate swan
#

😄

shrewd apex
slate swan
paper sluice
#

!ot

unkempt canyonBOT
cold sonnet
#

no u

cold sonnet
#

pride

slate swan
# vocal snow why are you passing ctx.author to it 😭
Ignoring exception in command dono add:
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Jaisman's PC\Desktop\ACLib\cogs\cogs\donation.py", line 50, in add
    await self.get_dono_ac(ctx.author)
  File "C:\Users\Jaisman's PC\Desktop\ACLib\cogs\cogs\donation.py", line 30, in get_dono_ac
    if str(ctx.author.id) in user:
AttributeError: 'Member' object has no attribute 'author'
```😭
vocal snow
#

i give up

#

@slate swan u help pls

slate swan
slate swan
#

I fixed it yesterday too, gave the same answer

#

Oh get-

slate swan
#

Hi

#

hello @slate swan

#

What is it that you seek

empty quest
#

is it:
pip install discord
or
pip install discord.py
or
pip install python-discord

slate swan
#

first one

empty quest
#

what about when importing?

slate swan
#

import discord

empty quest
#

what is discord rewrite?

slate swan
#

idk

#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '782880264572633118'
``` shouldn't the value be stored when i run `a?dono add`?
paper sluice
slate swan
#

how to take input and store it in an variablw

slate swan
paper sluice
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
paper sluice
slate swan
#

and wait for what?

slate swan
# paper sluice show code
@dono.command()
    @commands.has_permissions(administrator=True)
    async def add(self,ctx,member: discord.Member,*,amount: int):
        await self.get_dono_ac(ctx)
        users = await self.set_dono_ac(ctx.author,ctx)
        users[str(ctx.author.id)]["user_id"]

        if amount > 10000000000000:
            await ctx.send("Bro, you can't add that much into my db.")
        else:

            users[str(ctx.author.id)]["user_id"] = member.id
            users[str(ctx.author.id)]["donated_amount"] += amount

            total = users[str(ctx.author.id)]["donated_amount"]

            e = discord.Embed(title=f"Donation Added",color=discord.Colour.dark_theme())
            e.add_field(name="Amount Added:", value=f"{amount}", inline=False)
            e.add_field(name="Total Donations:", value=total)

            e.set_footer(text=ctx.guild.name,icon_url=ctx.guild.icon.url)

            await ctx.send(embed=e)

            with open("donations.json", 'w') as f:
                json.dump(users,f)
paper sluice
# slate swan what do i put in check?

depends on the event, if you are going to put an on_message then you need to put a function which takes message as argument
then you can do various check in there like message.author == ctx.author etc

slate swan
#

oooooh

slate swan
#

the input

paper sluice
slate swan
#

ooooooh

#

ookayy

paper sluice
paper sluice
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
paper sluice
#

right that error is because of get_dono_ac, i think you are trying to the access the data before its set

#
    user[str(ctx.author.id)]["user_id"] = 0

you are doing that while the dict users doesn't have the key with the id

slate swan
#

so what should i do?

paper sluice
#

store it before hand or use collections.defaultdict

brave flint
# slate swan right in that message, the args argument was a callable earlier, its a tuple wit...

after trying that for sending webhook i got infinite spam of RuntimeError: Task <Task pending name='Task-233' coro=<sendw() running at /app/bgtasks.py:21> cb=[_run_until_complete_cb() at /app/.heroku/python/lib/python3.9/asyncio/base_events.py:184]> got Future <Future pending cb=[shield.<locals>._outer_done_callback() at /app/.heroku/python/lib/python3.9/asyncio/tasks.py:910]> attached to a different loop

cold oyster
#

Hello, So my friend's discord server got nuked, So I want to make a bot which will delete all the channels with a specific name

#

Any way to do that with d.py?

paper sluice
#

!d discord.Guild.channels you can use this to get a list of all channels, then you can look for the channels you want to delete

unkempt canyonBOT
slate swan
vocal plover
# unkempt canyon

if you want a fairly idiomatic way to find those channels you could use something like filter(lambda c: c.name == "some-name", guild.channels)

paper sluice
brave flint
#

for me better like using data = [{"id":id,"data":data},] and so on

slate swan
slate swan
# paper sluice something like: `user[id] = {...}`
@hping.command()
async def set_pingrole(ctx,*,roleid: int):
  await set_role(ctx.guild,ctx)

  guilds = await get_role()

  guilds[str(ctx.guild.id)]["role"] = roleid
  guilds[str(ctx.guild.id)]["guild_id"] = ctx.guild.id

  await ctx.send(f"Successfully set the heist ping role to <@&{roleid}>")

  with open("hping.json", 'w') as f:
    json.dump(guilds,f)
``` same code with some difference but it works .
rough kraken
#

Hi, I want to create a discord bot for the user to be shown when he is active in a channel or when he enters in a channel. I tried to do research to build the algorithm because im new to bot development , but i do have experience in programming of Python and JS. The algorithm i plan to use is that when a member click on the channel, then obv he would be inside that channel, i could see the activity status by showing the time in the logs that he is online (lurking but not messaging) in the channel or not. I would really appreciate if someone help me regarding this bot development, any suggestions are welcome too. thanks!

sick birch
#

There is no such thing as "being inside a channel" as that's purely client-side

#

And an event for that is not dispatched to you

rough kraken
#

but i wanted to try

cold oyster
#
  client = commands.Bot(command_prefix=".")```

What is this supposed to be now?
slate swan
rough kraken
#

gotcha gotcha, thanks @sick birch @slate swan

slate swan
#

more like a hard NO as it will always be out of discord api's limitations as robin said 😔

cold oyster
#

How to enable 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.

sick birch
rough kraken
shrewd apex
#

don't forget to save

cold oyster
rough kraken
#

show code

shrewd apex
#

in commands.Bot do u have intents= discord.Intents.all()

cold oyster
# rough kraken show code
import disnake as discord
from disnake.ext import commands

client = commands.Bot(command_prefix=".")



@client.command(name='delete-channel', help='delete a channel with the specified name')
async def delete_channel(ctx, channel_name):
  guild = ctx.guild
  existing_channel = discord.utils.get(guild.channels, name=channel_name)
   
   # if the channel exists
  if existing_channel is not None:
    await existing_channel.delete()
   # if the channel does not exist, inform the user
  else:```
shrewd apex
slate swan
cold oyster
#

I only need message intents

shrewd apex
#

¯\_(ツ)_/¯

cold oyster
#

This is a private bot for my friend

slate swan
cold oyster
#

Anyways thx

shrewd apex
#

alr

slate swan
#

still

shrewd apex
#

ok every drop matter

slate swan
#

what if I say that you're gonna die but nobody cares

shrewd apex
#

single drops make a ocean

#

i get u completely

rough kraken
#

lmao Ashley 😂 girllll

slate swan
shrewd apex
#

😭 nitro flex even while exiting can't beat that ;-;

rough kraken
#

gib nitro toooo

shrewd apex
slate swan
shrewd apex
#

hmm bad eyesight then

slate swan
#

time to increase power of the lens

#

Qeustion in regards to the wait_for function; does the timeout para have to be present? I keep seeing it in nearly every wait_for code I have seen written just not my own 🙂

#

timeout para?

#

still not getting ti reight

shrewd apex
#

it dosent

slate swan
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
shrewd apex
#

but that way the wait_for event will wait until u break it somehow like return the function

slate swan
#

what even is a timeout para cathmm

cold oyster
# slate swan just do ```py intents = disnake.Intents.default() intents.message_content = True...
@client.command()
async def start(ctx, channel_name):
  guild = ctx.guild
  existing_channel = discord.utils.get(guild.channels, name=channel_name)
   
   # if the channel exists
  if existing_channel is not None:
    await existing_channel.delete()
   # if the channel does not exist, inform the user
  else:
    await ctx.send(f'No channel named, "{channel_name}", was found')```

Why wont it delete the channels?
slate swan
#

timeout is a "parameter" lol just couldnt be bothered writing the full word.

shrewd apex
cold oyster
slate swan
shrewd apex
cold oyster
#

nop

slate swan
#

what

cold oyster
slate swan
#

show intents

cold oyster
slate swan
#

in the code

shrewd apex
#

just show the whole code

slate swan
#

dont

shrewd apex
#

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

,

#

anyways ill be off

cold oyster
#

HELP?

#

@shrewd apex

slate swan
#

Stop pestering people.

cold oyster
#

🤓

slate swan
#

They are volunteers giving you their time for free.

shrewd apex
#

bro send code i cant see ur pc screen

shrewd apex
#

the whole code

cold oyster
#
import disnake as discord
from disnake.ext import commands

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

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



@client.command()
async def start(ctx, channel_name):
  guild = ctx.guild
  existing_channel = discord.utils.get(guild.channels, name=channel_name)
   
   # if the channel exists
  if existing_channel is not None:
    await existing_channel.delete()
   # if the channel does not exist, inform the user
  else:
    await ctx.send(f'No channel named, "{channel_name}", was found')```
shrewd apex
#

bot.run()?

#

u have that right

cold oyster
#

its online

#

client.run("no")

shrewd apex
#
import disnake as discord
from disnake.ext import commands

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

@client.command()
async def start(ctx, channel_name):
  guild = ctx.guild
  existing_channel = discord.utils.get(guild.channels, name=channel_name)
   
   # if the channel exists
  if existing_channel is not None:
    await existing_channel.delete()
   # if the channel does not exist, inform the user
  else:
    await ctx.send(f'No channel named, "{channel_name}", was found') 
cold oyster
#

What did you change

shrewd apex
#

try this also i think it was intents.message

vale wing
cold oyster
#

Huh?

vale wing
#

Just typehint

shrewd apex
vale wing
#

My thing is much shorter

cold oyster
shrewd apex
cold oyster
#

My friend's server got nuked

shrewd apex
cold oyster
#

Im trying to delete the channels named "kid"

shrewd apex
#

so it's not a command problem

vale wing
#

Ok

shrewd apex
cold oyster
#

Ill try

#

Nope

#

Nothing still

vale wing
#

Is bot online

cold oyster
#

Message I sent: .start kid

cold oyster
vale wing
#

Ok

#

Does it respond to simple response commands

#

And does it have permission to read messages in the channel you are using the commands in

cold oyster
shrewd apex
#

make a ping command

#

and try

vale wing
#

^

cold oyster
vale wing
#

In case that fails listen to on_message and print some message data including the fact of message receive and message content

cold oyster
vale wing
#

You forgot the brackets ig

#

discord.Intents.all()

cold oyster
#

YES

#

i did

shrewd apex
#

remove those two lines

cold oyster
#

other cmds work

shrewd apex
#

on top the defaul() and the other intent line

vale wing
cold oyster
vale wing
#

Doesn't work like doesn't give response or smth

cold oyster
#

Wait

#

Leme try the premium method: Print

#

@vale wing

vale wing
#

This means it worked?

cold oyster
vale wing
#

Why

cold oyster
#

Btw the error is smth else

#

my frnd typed: ...

vale wing
#

It reached the statement it was supposed to reach

vale wing
cold oyster
cold oyster
vale wing
vale wing
cold oyster
#

If I remove the arg channel name and like tell it to delete a specific channel will it work?

cold oyster
vale wing
#

You might not even notice that it has been deleted

#

Check audit logs

#

And use for loop to delete them all

cold oyster
#

my fucking god

#

IT IS DELETING THEM

#

but how do i make it a loop

vale wing
#

Like

for channel in ctx.guild.text_channels:
    if channel.name == "kid":
        await channel.delete()```
^ potentially dangerous code btw be careful not to erase the entire server
cold oyster
#

i cant use it

#

the server is big

cold oyster
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

vale wing
#

Just make sure to put the right condition

cold oyster
#

ill try

vale wing
cold oyster
#

It does

#

People can use it to make grief bots

vale wing
#

It basically deletes all channels named "kid"

cold oyster
#

WHere do I put this the for loop

vale wing
#

In your start command body ig

#

And it would look a bit differently

cold oyster
#

tysm

#

@vale wing Tysm

#

It worked properly

vale wing
#

Cool

cold oyster
#

And thanks for teaching me the for loop lol

#

I never knew how to do that

vale wing
#

M yes basic python

shrewd apex
#

actually why not just clean up the channel

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
cold oyster
#

There are channels, Not messages

#

Oh text channel

#

idk

#

I like it this way

shrewd apex
#

clear the channel by clearing all messages

neat field
#

well there is an issue if the messages are too old

shrewd apex
#

it got nuked recently so

cold oyster
#

There were only channels

#

No messages

shrewd apex
#

oh alr then

#

i am not sure but if there is a channel created time property u can use that to loop

warm tulip
#

guys this is my code for warn cmd :

  @commands.command(name="warn")
  async def warn(self, ctx: commands.Context, target: discord.Member, *, reason):
      await target.send(f"{reason}")
      await ctx.send("Mmeber Warned :white_check_mark:")

and i wanna do soemthing that onlly members with time_out_member permision can use this cmd how?

ashen notch
#

At least not from the regular endpoint

ashen notch
#

I think there's a decorator with that.... One sec

warm tulip
#

😢

slate swan
unkempt canyonBOT
ashen notch
#

Oh I'll be damned

warm tulip
#

guys this is my code for warn cmd :

  @commands.command(name="warn")
  async def warn(self, ctx: commands.Context, target: discord.Member, *, reason):
      await target.send(f"{reason}")
      await ctx.send("Mmeber Warned :white_check_mark:")```

and i wanna do soemthing that onlly members with time_out_member permision can use this cmd how?
slate swan
#

everything with an ID in discord.py has a created_at attribute, since discord provides snowflakes that way

warm tulip
slate swan
#

atleast they get warned

slate swan
slate swan
warm tulip
#

i have 1.7.3

slate swan
#

sad then have fun

#

oh, ash already provided that

slate swan
#

unless the moderators suck

warm tulip
#

@commands.has_permissions(timeout_members=True)
will this works?

slate swan
#

nope

warm tulip
#

y

#

wwwyy

slate swan
#

thats not a valid permission

warm tulip
#

so

#

what is timeout members perm

ashen notch
#

Is it m- yep, beat me to it

slate swan
#

*moderate_members

warm tulip
#

whyyyyyyyyy

#

python why you dont have timeoutttt

#

emoji_20 yyyyyyyyyy

slate swan
#

it does. you need to use the updated version of the library...

warm tulip
#

how i can update it

slate swan
#

first, install git on your device if you don't have it already

warm tulip
#

😐

slate swan
#

then run this command ```
pip install -U git+https://github.com/Rapptz/discord.py

#

there are lots of breaking changes so you'll have to refactor your code.

warm tulip
#

will the cmds reset?

slate swan
#

most of them wont

slate swan
#

you'll have to change 10-15 lines.

slate swan
#

ash is a professional bully

#

stahp

#

no.

slate swan
slate swan
warm tulip
#

i used manage message 😐

glad cradle
#

😶

faint sapphire
#

im using heroku and github to host my bot

do i need to have this runtime file to indicate which python version to use?

shrewd apex
#

u just need to add the python buildpack

faint sapphire
cloud dawn
#

Hemlock trying to beat a competitive beat to the question user.

slow fog
faint sapphire
#

what i should see

#

vs what i see
bot wont turn on

void flax
#

node is a javascript runtime, it doesn't run python code

faint sapphire
#

i messedup yh, cause i had put in smtg wrong in procfile, i had changed it but didnt save it :/

#

thanks for poiting it out

#

i hope it works when i retry

#

it works

#

if i want to update my script
do i just deploy my github project again?@void flax

void flax
#

idk how you have heroku set up for deploy

#

I know they had something where it would redeploy automatically when you push to github, but I think you have to set it up

#

they also have their own repo, where you set a different remote in git

#

and you can git push heroku main

#

after you git remote add heroku <heroku remote url>

#

isn't there a deploy tab or something in the heroku project? Look there and see how you can do it

faint sapphire
#

i have it on automatic but i still did deploy

#

from the github desktop i update the github project

austere vale
#

anyone know a good tutorial of some sorts for a leveling database

paper sluice
vale wing
#

It's just id - score lol

slate swan
#

yes, but with _guild added to it

#

!d discord.on_guild_channel_create

unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").

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

how could i get this from a message?

slate swan
unkempt canyonBOT
slate swan
sleek gyro
#

but it gives me the UTC time

slate swan
#

!d datetime.datetime.astimezone

unkempt canyonBOT
#

datetime.astimezone(tz=None)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object with new [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") attribute *tz*, adjusting the date and time data so the result is the same UTC time as *self*, but in *tz*’s local time.

If provided, *tz* must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and its [`utcoffset()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcoffset "datetime.datetime.utcoffset") and [`dst()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.dst "datetime.datetime.dst") methods must not return `None`. If *self* is naive, it is presumed to represent time in the system timezone.

If called without arguments (or with `tz=None`) the system local timezone is assumed for the target timezone. The `.tzinfo` attribute of the converted datetime instance will be set to an instance of [`timezone`](https://docs.python.org/3/library/datetime.html#datetime.timezone "datetime.timezone") with the zone name and offset obtained from the OS.
slate swan
#

you can convert it to your own

#

you would have to access the server audit logs for that

#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
slate swan
#

you cant do it then