#discord-bots

1 messages Β· Page 960 of 1

slate swan
#

events work in my bot in events.py and then i import them in my main bot and then i just do

@client.event
async def on_message():
    sussy(client, message)
hushed galleon
#

you can store the currently running games in a variable and check to see if one's running

#

assuming the game doesnt last for too long

pure sparrow
#

Nice selfie 🀩

narrow grail
#

where one player is waiting for the other from an other server

pure sparrow
#

you have to creat a list like list = [« sus »]

narrow grail
hushed galleon
#

well what did you try? and what version of dpy are you running? dpy 2.0 and forks of dpy like disnake offer discord's new timeout feature which would be suitable for doing mutes

slate swan
#

user = message.author
role = get(user.server.roles, name="Muted")
await client.add_roles(user, role)

pure sparrow
#

@slate swan Add me to be friend I have a part of my code that I can send to you. My pc is off so I will help you tomorrow

glacial echo
#

whats the standard right now for virtual environments

pure sparrow
#

I know what you mean

hushed galleon
#

client.add_roles is extremely outdated and has been replaced with Member.add_roles(<one or more roles>)

slate swan
#

oooooooh

hushed galleon
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate swan
#

but how do i make it for an selected user

#

like message.author or something

pure sparrow
#

message.author means that it’s the author of the message so it works with it

hushed galleon
# narrow grail My idea was to make a queue

yeah that would probably be a good idea, although after two players connect then you'll still want a way for your game to run; this could be done with a custom class that keeps track of game variables and listening for messages from the appropriate players

pure sparrow
#

Add me I will help you tomorrow

slate swan
#

you need to add me first

#

you disblaed it

hushed galleon
pure sparrow
#

oh

narrow grail
pure sparrow
abstract kindle
#

Where do I get the docs for Buttons, TextInputs et

hushed galleon
abstract kindle
#

oh okay, that's why I'm lost

hushed galleon
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
hushed galleon
#

you'll find the rest there

abstract kindle
#

Thanks ❀️

#

Are text inputs working

hushed galleon
#

i assume they are, there's an example modal on the repo

slate swan
abstract kindle
#

sweet

slate swan
#

How can I limit someone from using a command if they already used it and it is still running?

narrow grail
hushed galleon
# narrow grail may you send me an example of your idea?
minigame_queue = []``` for simplicity a list could be used as your queue, and you might append either a user or a (user, channel) tuple to it, whatever you might need, then your class might look like this ```py

class Minigame:
    def __init__(self, bot, player_channels): ...
        # store whatever attributes you may need such as the bot,
        # or the players and the channels they're in

    # if you need to write helper functions for your game,
    # this class can keep them organized in one place

    async def start(self):
        # send a message to each player...
        # wait for player A's turn... (see wait_for docs)
        message = await self.bot.wait_for('message', check=check)
        # ...and anything else here``` then you could use the queue and class in your command ```py

@bot.command()
async def join_minigame(ctx):
    # add the player to queue if they are the first one
    if not minigame_queue:
        minigame_queue.append(ctx.author)
        return

    # otherwise pick the first player in queue
    other_player = minigame_queue.pop(0)

    # then start the minigame
    my_game = Minigame(bot, [ctx.author, other_player])
    await my_game.start()```
hushed galleon
hushed galleon
unkempt canyonBOT
#

@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.
hushed galleon
#

if they exceed the max number then the decorator raises a commands.MaxConcurrencyReached error

slate swan
# unkempt canyon

what is the * there for and where do I put that in my code? below, above, or inside my command class?

cloud dawn
#

!args-kwargs

unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
β€’ Decorators (see !tags decorators)
β€’ Inheritance (overriding methods)
β€’ Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
β€’ Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

hushed galleon
#

the * means any parameters after it are keyword only, and its something you can do in your own functions

#

e.g. ```py
def add(*, x, y):
return x + y

now you are required to use keyword arguments

add(x=1, y=2)
3```

#

and max_concurrency is a check decorator so it would be on top of your command: py @bot.command() @commands.max_concurrency(1, commands.BucketType.user) async def my_command(ctx): ...

slate swan
#

fuck it since i cant get it working ill just make it ban people troll

slate swan
hoary cargo
#

CatAwk what are you talking about
That's me

slate swan
#

hey uhh this code is only mentioning the bot who sent that message

bot.mention for bot in ctx.guild.members if bot.bot```
its supposed to show the others too
final iron
#

!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 the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

this is the bots embed guildinfoEmbed.add_field(name='Bots', value=', '.join(list_of_bots), inline=False)

slate swan
sick birch
#

β€œIf bot.bot”

junior verge
#

yeah lol

slate swan
#

what do i change it to

sick birch
#

So it only adds all members that are bots

slate swan
#

yea thats what its supposed to do

#

but it doesnt do that

sick birch
#

So it mentions all users?

slate swan
#

no i mean so it mentions every bot in the server

#

https://hypixel.net/||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​|| https://i.e-z.host/β€Œβ β€Œβ€Œβ€Œβ β β€β€‹β€β β€Œβ β€β€Œβ€‹β€Œβ€Œβ€‹β€Œβ€‹β€Œβ€‹β€β€‹β€‹β€‹β€Œβ€Œβ β€‹

hypixel.net image host!
sick birch
#

And what's it doing right now?

slate swan
sick birch
#

Which bot?

slate swan
#

https://hypixel.net/||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​|| https://i.e-z.host/β€Œβ€β β€‹β β€β€β€‹β β€Œβ€‹β€‹β€β€β€β€β€β€Œβ β β β β€Œβ β β€‹β β β€β€Œβ€‹

hypixel.net image host!
#

my own bot

sick birch
#

Is that the only bot in the server?

slate swan
#

nope

sick birch
#

Then it's probably an intents issue

slate swan
#

intents issue?

sick birch
#

Yes.

slate swan
#

should i send code

sick birch
slate swan
#

uhh u cant use intents in brakcets

inner wing
#

If someone from Israel please dm me

sick birch
#

What?

hushed galleon
# slate swan intents issue?

yeah if you dont have the members intent enabled, discord.py cant offer you a list of members in the guild and the discord API will prevent you from requesting them

junior verge
#

Just applied for verified bot, how long does the response usually take?

slate swan
#

https://hypixel.net/||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​|| https://i.e-z.host/β β€β β€‹β€Œβ€β β€Œβ β€Œβ€β β€‹β€β€‹β€β β€Œβ€Œβ€‹β β€β€β€Œβ€Œβ β€β€‹β β€Œβ€‹

hypixel.net image host!
glad cradle
#
  @commands.command()
  @has_permissions(ban_members =True)
  async def ban(self, ctx, member: disnake.Member = None, *, reason = None):
    logsChannel = self.bot.get_channel(877143830955180102)
    
    if member == None:
      
      embed = disnake.Embed(
        title=f'Errore',
        color=disnake.Color.from_rgb(255, 1, 57),
        description=":x: Devi specificare un membro da bannare per poter usare questo comando!"
      )
      await ctx.reply(embed=embed)


    elif member != None:
      
      embed = disnake.Embed(
        title=f'Membro {member.name}#{member.discriminator} bannato!',
        description=f"{member.name}#{member.discriminator} Γ¨ stato bannato da {ctx.author.name}#{ctx.author.discriminator}",
        color=disnake.Color.from_rgb(255, 1, 57),
        timestamp=datetime.datetime.utcnow()
      )
      embed.set_author(
        name=f"Comando eseguito da {ctx.author.name}#{ctx.author.discriminator}"
      )
      await member.ban(reason=reason)
      
      await logsChannel.send(
        f"`[{datetime.datetime.utcnow().strftime('%H:%M:%S | %d-%m-%Y')}]` **{ctx.author.name}#{ctx.author.discriminator}**\n(ID:{ctx.author.id}) ha bannato un utente:",
        embed=embed
      )

when I try to ban nothing happens, I don't get any errors, can you help me?

slate swan
#

wtf??

junior verge
glad cradle
junior verge
#

No I am just asking you something

junior verge
#

I applied my bot for verified

glad cradle
junior verge
#

To what?

glad cradle
#

to str

hushed galleon
junior verge
#

yeah lol

junior verge
sick birch
#

Though they often get behind

junior verge
#

My bot is growing like 20 servers a day, it's a 100 now so can't grow till it's verified :/

glad cradle
sick birch
echo elbow
#

A quick question for the mods,
can I post here that I'm looking for a partner to help me develop a discord bot using python or is it against any of the rules?

sick birch
echo elbow
#

I figured it would be something like that, even though i'm technically not interested in advertising the project itself, but looking only for a partner

hushed galleon
glad cradle
#

figured it out with an errors handler
Command raised an exception: Forbidden: 403 Forbidden (error code: 60003): Two factor is required for this operation

sick birch
#

Ah

hushed galleon
#

the server requires 2FA which means the bot dev also needs to have 2FA as well

glad cradle
#

yes

#

πŸ˜”

hushed galleon
#

first time ive seen that error message

slate swan
#

File "c:\Users\acatto\Desktop\NSB\main.py", line 9, in <module>
from discord.ext import commands, tasks
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)

#

umm

glad cradle
slate swan
wispy spade
#

sure you just don't have a file named discord in the same place as main.py?

slate swan
#

https://hypixel.net/||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​|| https://i.e-z.host/β β€Œβ β€‹β€Œβ€‹β€β€Œβ β€‹β β€β€‹β€Œβ€Œβ€‹β β β€Œβ€β€β€Œβ β€Œβ€Œβ€β€β β€β β€‹

hypixel.net image host!
#

should i pip uninstall discord and install it again

sick birch
#

Give that a try

slate swan
#

imma try nextcord

hushed galleon
junior verge
#

@sick birch What would you say that is the easiest way to get slash commands without changing too much of your code

narrow grail
hushed galleon
#

just writing it somewhere in your global scope is fine, or as a bot var if you have a cog and want it to persist across cog reloads

hushed galleon
#

with the equal sign?

#

!e py a_variable = 123 print(a_variable)

unkempt canyonBOT
#

@hushed galleon :white_check_mark: Your eval job has completed with return code 0.

123
slate swan
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

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

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
#

oops

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 'discord' is not defined
slate swan
unkempt canyonBOT
#

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

discord.py is confusing
hoary cargo
narrow grail
#

looks wrong

hearty island
#

Who knows how to fix this?

hoary cargo
dire folio
hearty island
#

pipinstaller : The term 'pipinstaller' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1

  • pipinstaller getuuid.py
  •   + CategoryInfo          : ObjectNotFound: (pipinstaller:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
hoary cargo
#

What are trying to do CatAwk

cloud dawn
#

Convert his code to .exe

hearty island
#

py - exe

sick birch
hearty island
#

to get uuid

dire folio
#

???

hearty island
#

it'll print it in cmd promt

sick birch
#

Think you NEED it before doing it

hearty island
#

yeah i do

cloud dawn
#

c# is such a fine language 😰

sick birch
hearty island
#

its for a whitelist and blacklist system so i can blacklist ur uuid

sick birch
#

For a discord bot?

hearty island
#

yh

dire folio
sick birch
#

I don't see why you need an executable for that

hearty island
#

no like

sick birch
#

Just keep it a regular .py file

#

No need to mess with the weird py installers

dire folio
#

^

hearty island
#

kk

sick birch
#

Putting an interpreted language into an executable only adds more overhead

hoary cargo
sick birch
#

People seem to want to put everything into an executable

#

I can understand that since it's all in one nice package but unfortunately that's not how interpreted languages work

hoary cargo
#

"It's cool" TrollGlitch

sick birch
#

If you want everything to be in one nice little executable file, you should program in a compiled language

pliant gulch
#

Just ship the python bytecode kek

sick birch
#

Don't you still need the interpreter for that

pliant gulch
#

You would still need the interpreter so it’s totally useless

sick birch
#

Thought so

#

The only time I've seen a need for converting python files to executables is when someone writes a malware in python, and sending a py file would be too easy to figure out

pliant gulch
#

Make a python program that takes python code interpreting it to C then compile that kek

sick birch
#

shit

pliant gulch
#

Kind of weird to require UUID whitelisting for a discord bot

sick birch
#

time to get demoted for rule 5

pliant gulch
#

Leaves me to believe the bot was made for malicious purposes

narrow grail
#

@hushed galleon sorry got it but what to put in the list?

hoary cargo
sick birch
#

Nah. They probably just want a whitelist/blacklist system

narrow grail
pliant gulch
#

A normal bot would’ve use discord IDs?

sick birch
#

UUID is strange yes, you could just use their discord ID

cloud dawn
sick birch
#

They'd still have to download python.

#

Well, not them

hoary cargo
#

hmmnote if you don;t plan updating your bot ever i guess you might turn it into an exe

flat solstice
cloud dawn
#

what is event_admins?

#

ah

sick birch
#

The pitfalls of dynamically typed languages

flat solstice
hoary cargo
flat solstice
#

I think they should really just allow us to input a custom colour

somber sky
#

how do i make if they click a different option it returns something different

silent ermine
narrow grail
#

@hushed galleon how to send the game start message to both channels?

hushed galleon
#

youd store both of the player's channels beforehand and then send to them when your game starts

hushed galleon
#

@narrow grail

dusk pumice
#

Is there any apis for the welcome image?

#

Or should I use PIL to make it

#

Anyone here?

hybrid ravine
hybrid ravine
dusk pumice
potent otter
#

I'm trying to make an on_message for a server of mine, where if there is no image attachment it deletes the message
but if there is, it keeps it
ex:

#screenshots (only images)

user says something, it deletes
user attaches image and says something, it stays

slate swan
#

how would i delete a stage with py? (only works for someone with a certain role)

tawny smelt
#

Hiho!
I've made a discord.py bot command:

@bot.command()
async def remind(ctx, *msg_parts):
    ...

and as you can see, I'm taking *args from the message. The problem is: when I put one quotation mark " in the message, I get an error: discord.ext.commands.errors.ExpectedClosingQuoteError: Expected closing "..
I have some idea why it's this way, but I don't have any idea about how to solve it. Could I get a hint? πŸ™‚

sick birch
#

It's meant to be

async def my_command(ctx, *, arg_name):
  ...
slate swan
#

wsp

#

i need some help wit this code rq

#

ion know why it aint workin

tawny smelt
potent otter
slate swan
sick birch
#
    HC = discord.utils.get(guild.roles, name="Head Coach")
    await user.add_roles(HC)
#

This won't quite work;

#

First check if they have HC role, if so, give GM role (optionally remove HC role), if not, give them HC role

#

You're halfway there already

slate swan
#

it gives them both roles

sick birch
#

You're checking if they have HC role, but you don't have an else condition

#
if HC in user.roles:
  # give GM role
else:
  # give HC role 
slate swan
#

o

potent otter
#
@client.event
async def on_message(msg):
if (msg.channel.name == 'screenshots'):
      if not (msg.attachments) or ('https://cdn.discordapp.com/attachments/' in msg.content):
        # delete message

Need help with this, I'm not that good at discord.py and wanted to see how I can delete a message that has no attachment on message.

sick birch
#

No need to check for the link

potent otter
#

How would I do that?

#

Or should I remove msg.attachments and add if not ('https://cdn.discordapp.com/attachments/' in msg.content):

sick birch
#
if not msg.attachments:
  # delete
potent otter
#

ah

flat solstice
potent otter
#

@sick birch
I recieve this error
TypeError: 'in <string>' requires string as left operand, not list

@client.event
async def on_message(msg):
  if (msg.channel.name == 'musa-moment'):
      if not msg.attachments in msg.content:
        await msg.delete()
slate swan
potent otter
feral lichen
#

hi pog πŸ™‚

slate swan
#

ion know

supple thorn
cloud dawn
potent otter
flat solstice
cloud dawn
tawny smelt
#

Do I have to sanitize user input in commands that take keyword-only arguments? Like in !remind word1 word2: do I have to escape any characters or discord.py / python does it for me?

lucid vine
#

how would i use discord.ext.tasks.loop in this case

#

since after the first await it should sleep to the next like 10s

potent otter
#

Message is repeating over and over again:

@client.event
async def on_message(msg):
  if (msg.channel.name == 'πŸ“·β•Ώscreenshot-plane-spot'):
      if not "https://cdn.discordapp.com/attachments/" in msg.content:
        await msg.delete()

  if ((" release" in msg.content) or ("release " in msg.content)):
    await msg.reply("We are currently in a big development build up phase. Please check [#922607045969051698](/guild/267624335836053506/channel/922607045969051698/) for release information.")

  await client.process_commands(msg) 
lucid vine
cloud dawn
# potent otter Message is repeating over and over again: ```py @client.event async def on_messa...
@client.listen()
async def on_message(msg):
  if (msg.channel.name == 'πŸ“·β•Ώscreenshot-plane-spot'):
      if not "https://cdn.discordapp.com/attachments/" in msg.content:
        await msg.delete()

  if ((" release" in msg.content) or ("release " in msg.content)) and not msg.author.bot:
    await msg.reply("We are currently in a big development build up phase. Please check [#922607045969051698](/guild/267624335836053506/channel/922607045969051698/) for release information.")
hoary cargo
potent otter
#

Thank you, I had this issue before I just forgot how to fix it.

cloud dawn
slate swan
#

Sry idk

cloud dawn
lucid vine
#

No im asking for how to use it when it has a sleep function inside of it aswell

lucid vine
#

Why are u telling me that

somber sky
#

how would i make it add a reaction to the channels message. Check and X is defined at the begining of the code.

cloud dawn
# lucid vine Why are u telling me that
from discord import Game
from discord.ext import tasks
from discord.ext.commands import Cog, Bot


class Example(Cog, name='example_cog'):
    def __init__(self, bot: Bot) -> None:
        self.bot = bot
        self.precences = [
            "Hello!",
            "Do a flip!"
            ]
        self.loop_change_status_iteration = 0
        self.change_status.start()

    def cog_unload(self) -> None:
        self.change_status.cancel()

    @tasks.loop(seconds=10, reconnect=True)
    async def change_status(self) -> None:
        await self.bot.wait_until_ready()
        await self.bot.change_presence(
            status=discord.Status.idle, 
            activity=discord.Game(self.precences[self.loop_change_status_iteration])
            )

        self.loop_change_status_iteration += 1
        if len(self.precences) == self.loop_change_status_iteration:
            self.loop_change_status_iteration = 0


def setup(bot: Bot) -> None:
    bot.add_cog(Example(bot))
lucid vine
#

So the sleep inside and the loop sleep dont effect each other

cloud dawn
#

No?

#

I'm using a class to keep track of what iteration we're on.

#

If the amount of iterations is equal to the list reset to zero.

boreal ravine
hybrid ravine
#
ss = requests.post(f'https://discord.com/api/v9/channels/{f}/webhooks', headers=headers, json=json)
```how would i go about returning the urkl of this webhook?
quaint epoch
#

so i got a question

sick birch
quaint epoch
#

will await member.unban() work? considering that the member object has already been banned?

sick birch
#

That's the webhook URL isn't it? You're posting to it

quaint epoch
#

if you store the banned member obj in a list for like, 10 mins, will .unban() unban them?

#

or no

sick birch
#

Experiment

cloud dawn
quaint epoch
sick birch
#

But you can get the snowflake from them either way

quaint epoch
sick birch
#

It should, since you can easily get a snowflake from member objects

cloud dawn
cloud dawn
#

This server is not meant for this.

gentle wren
#

sry

cloud dawn
gentle wren
#

k

hybrid ravine
sick birch
#

Why not use d.py's method? I'm sure it returns the created webhook

hybrid ravine
sick birch
#

Sure. Use random.choice()

hybrid ravine
#

but it comes up wit invalid type

sick birch
patent lark
#

hm.

hybrid ravine
hybrid ravine
sick birch
hybrid ravine
sick birch
#

What type if f?

#

A list of IDs?

hybrid ravine
#

str. but i tried int

sick birch
#

It needs to be a channel object

slate swan
#

whats he tryna do

sick birch
#

If it's a list of IDs you can map or use list comps

sick birch
slate swan
sick birch
#
list_of_ids = [123, 456, 789]
channel_objects = [bot.get_channel(id) for id in list_of_ids]
#

Or, preferably, if keep it as a list of channels from the start

boreal ravine
#

or.. ```py
from random import choice

channel = choice(ctx.guild.text_channels)

sick birch
#

Why would you import it then use random.choice()

boreal ravine
hybrid ravine
sick birch
#

You have to use random.choice on it

hybrid ravine
slate swan
#

hmmmm

hybrid ravine
#

or do i put thw whole thing in random.chice

sick birch
#

Gotta await it but yes

slate swan
#

yo @sick birch can u help me w sum rq

hybrid ravine
sick birch
#

Is the list empty?

slate swan
#

await stage1.set_permissions(ctx.guild.default_role, move_members=False)
await stage1.set_permissions(ctx.guild.default_role, mute_members=False)

only denying mute permissions & the move permissions are still neutral and gray
@sick birch

pallid marsh
#

Can someone help me? I’m having trouble changing the bots nickname. I’m using v1.7.3

await client.user.edit(nick=β€œnick”)```
slate swan
#

am i doing something wrong

hybrid ravine
magic ore
pallid marsh
slate swan
magic ore
unkempt canyonBOT
#

property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
magic ore
#

has an edit method

pallid marsh
#

So then discord.Guild.me.edit?

arctic tangle
hybrid ravine
magic ore
#

you would access the me attribute of a Guild object (or Context object) and call the edit method on it

#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
pallid marsh
#

ah ok, thanks

slate swan
#

@magic ore yo? u mind helping me

#

await stage1.set_permissions(ctx.guild.default_role, move_members=False)
await stage1.set_permissions(ctx.guild.default_role, mute_members=False)

only denying mute permissions & the move permissions are still neutral and gray

magic ore
#

looks fine to me, make sure your bot has the right permissions

slate swan
#

it does

#

i can inv u to my test serv

#

and give u admin perms idk why it isnt

#

working

#

its for a stage channel so idk if that shit works differently

#

@magic ore its resetting the move member permission as it does it idk why

#

nvm i found out y

grim coral
#

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

client = MyClient()
client.run('Token you though u were gonna get that L')```
grim coral
#

Is this good so far this is my first project I started on so far and I need some feedback from this is there anything I need to improve on it?

supple thorn
#

it inherits from discord.Client so it has all of it's features with more

#

like commands so you don't have to make a bunch of if statements checking if a message has your prefix and command name

grim coral
#

yea

supple thorn
#

like your first python project?

grim coral
#

yes

supple thorn
#

damn good luck

grim coral
#

Thanks I like taking a challenge because I am wanting to learn from this.

vocal walrus
#

Hi! This is my first time making a discord bot using python

`@commands.command()
async def play(self,ctx,url):
    ctx.voice_client.stop()
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    YDL_OPTIONS = {'format':"bestaudio"}
    vc = ctx.voice_client
    await ctx.send("Playing!")

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
        info = ydl.extract_info(url, download=False)
        url2 = info['formats'] [0] ['url']
        source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
        vc.play(source)`

So i'm making a discord music bot here, but when i want to play something i get this error

grim coral
unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
vocal walrus
#

oh wait i forgot they didn't make it available now

#

okay thanks!

boreal ravine
slate swan
#
@client.event
async def on_message(message):
  try:
    if message.author.bot:
        return
    for attch in message.attachments:
        if (
            attch.filename[-4:] in ['.jpg', '.png', '.jpeg']
            and str(message.channel.id) == str(959954871656796223)
            ):
                user_points = get_config("points")
                user = message.author
                key = f"{user.name}#{user.discriminator}"
                user_points[key] = user_points.get(key, 0) + 1
                save_config("points", user_points)
  finally:
    # let other commands run
 
    await client.process_commands(message)

wondering how I can make it send an embed whilst replying to the user who sent the image

#

want it to reply to the image with this

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").

New in version 1.6.

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

yes I know that, but im confused where I'd put my embed and stuff

supple thorn
slate swan
#

no like literally my embed contents, where would I put them without messing up the rest

supple thorn
#

put them inside a embed then

slate swan
#

what indentation and after what part

#

like do they go after the finally etc.

supple thorn
slate swan
#

for the await client.process_commands(message)

supple thorn
#

for what actual reason do you have that there for

slate swan
#

someone suggested using it a longgg time ago

supple thorn
#

πŸ—Ώ

slate swan
#

?

supple thorn
slate swan
#

it has been working good though

supple thorn
#

literally no reason to use them

#

you're not even catching errors with an except block

slate swan
#

because up until now I didn't need to

#

can you help or are you gonna criticize all of it 🀣

supple thorn
#

and put the process_commands on the first level

slate swan
#

Which line

echo wasp
#

How can you check if message.content contains something?

supple thorn
#

at the end

#

but on the first level indentation

supple thorn
#

or

echo wasp
slate swan
supple thorn
#
if message.content.startswith("&"):
  ...
slate swan
#

or that yeah

supple thorn
slate swan
#

ah gotcha

supple thorn
#

that would trigger if any & is in the message

#

rather it being the first thing

slate swan
#

yeah I didnt read his last message

#

ok so back to my code

supple thorn
slate swan
#

you want me to move await client.process_commands(message) on the same level as save_config?

supple thorn
#

bruh

#

no

supple thorn
slate swan
#

yes

supple thorn
#

it has to be the same indentation line like the first if statement

#

but on the last line

#

or just use bot.listen

slate swan
#

4th line is the first if statement

supple thorn
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
#

@client.listen() ?

supple thorn
#

you don't have to process commands with this

supple thorn
slate swan
#

πŸ˜„

#

why lol

supple thorn
#

not a client

#

also confusing because discord.Client exists

austere vale
#

can someone help me with this?

  @commands.command()
  @commands.has_permissions(administrator=True)
  async def unban(self,ctx, *, member):
      banned_users = await ctx.guild.bans()
      member_name, member_discriminator = member.split('#')
      for ban_entry in banned_users:
          user = ban_entry.user
          if (user.name, user.discriminator) == (member_name, member_discriminator):
               await ctx.guild.unban(user)
               await ctx.channel.send(f"Unbanned: {user.mention}")
supple thorn
#

it's like doing this

solar summit
supple thorn
#
string = 1
number = "my string"
solar summit
#

@austere vale why do you have *, ?

austere vale
#

is * not needed?

slate swan
#
  • is all isn't it?
solar summit
#

if you're passing in the @ then why would you

#

its a single word

supple thorn
solar summit
#

same as ColdLuck#6969

slate swan
solar summit
#

it wont be ColdLuck # 6969 where you need to see all those words

#

even if you did, with your code it causes errors

supple thorn
#

big dreams

austere vale
#

thank HAHA

slate swan
#

@supple thorn what do I set as the name for the .listen and what does it matter?

supple thorn
slate swan
supple thorn
slate swan
#

thats what I use

echo wasp
supple thorn
#

yeah works but can be better

echo wasp
#

Right?

supple thorn
slate swan
#

ye

supple thorn
#

i don't know why he turns them into a string

solar summit
echo wasp
supple thorn
#

useless to turn them into a string when they are both already a int

supple thorn
slate swan
#

so does the name matter?

supple thorn
#
@bot.listen("on_message")
async def quack_messages(message):
  ...
supple thorn
#

then yes

#

if no

slate swan
#

In my case for detecting on message does it matter

supple thorn
#

just don't put anything for the name

#
@bot.listen()
async def on_message(message):
  ...
slate swan
#

Ah ok

#

and that wont interfere with my .event ?

austere vale
#

how do i fix this?

  @commands.command()
  @commands.has_permissions(administrator=True)
  async def unban(self,ctx, member):
      banned_users = await ctx.guild.bans()
      member_name, member_discriminator = member.split('#')
      for ban_entry in banned_users:
          user = ban_entry.user
          if (user.name, user.discriminator) == (member_name, member_discriminator):
               await ctx.guild.unban(user)
               await ctx.channel.send(f"Unbanned: {user.mention}")
solar summit
austere vale
#

oh

solar summit
#

can you get rid of your error handler and send the error here

#

also dont copy and paste code, this is why you're running into errors and dont know how to fix it

austere vale
torn sail
#
  1. It needs to be name#1234 2. U can use id mention etc by using discord.User typehint and ctx.guild.unban
#

The way ur using is bad

solar summit
#

copy pasting code...

slate swan
#

attch.filename[-4:] in ['.jpg', '.png', '.jpeg']
NameError: name 'attch' is not defined

i define it above though idek

#

show code

solar summit
#

how dont u know lol

slate swan
#

probably mispelled

#

"attch"

modest plover
#

Anyone here know how to host a bot using railway?
I'm having issues

#

I'm trying to host the bot but it fails during the build

solar summit
#

railway?

modest plover
#

Yes

#
Railway

Railway is an infrastructure platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.

solar summit
#

no idea I would just recommend buying a $2 vps

modest plover
#

I have all my bot code in a repo but it's seperated by folders in the repo per bot

solar summit
#

or even heroku i think is simpler

modest plover
modest plover
solar summit
#

i think thats more of a railway problem then a discord.py problem..

lucid vine
#

i have 2 questions one is how do i for example like i have a prefix command that saves the guild id and prefix to a json and i want to like reply with that set prefix when i mention the bot how do i extract the prefix again? and other question is how would i do like categories in a help cmd embed like dank memer

#

like this

slate swan
slate swan
#

ah i got it

slate swan
#

so you can't give reason for unban

#

include that first

lucid vine
slate swan
#

you would need to use 2.0 or a fork

lucid vine
# slate swan no

if i use 2.0 will my commands ect go to waste like be unusable and ill have to use the new 2.0 lib and docs to make my bot again?

slate swan
lucid vine
#

okay ill try, worst case ill have to get back to 1.7.3

slate swan
#

good luck

lucid vine
slate swan
#

!d discord.ext.commands.Bot.get_prefix

unkempt canyonBOT
#

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

Retrieves the prefix the bot is listening to with the message as a context.

Changed in version 2.0: `message` parameter is now positional-only.
lucid vine
#

@slate swan and to install dpy 2.0 i need python 3.6?

#

cant i do it with 3.10

slate swan
#

so 3.10 works

lucid vine
#

okay ty

austere torrent
#

is there any way to get the id of a previous message in a specific channel? like i need the id for the second to most recent message, not just the most recent one

#

i know await channel.history(limit=2).flatten() can get me a list that contains the id, but i dont know how to 'extract' it per say

glacial willow
slate swan
#

use just 1 bot instance

austere torrent
#

did you import discord?

#

what exactly is the error

#

i'm not sure then, maybe someone else will know

lucid vine
#

@slate swan ive installed 2.0 and added the intents and now none of my cmds are working did i do anything wrong because im not getting any errors has anything else exceptionally in my case what im having a problem with changed?

#

maybe its cuz of my custom prefix line

supple thorn
#

try removing that for now

#

and just put a test prefix in it's place

lucid vine
#

client = command.Bot(command_prefix= get_prefix, intents=intents)

is that correct

lucid vine
supple thorn
#

client

#

πŸ˜”

lucid vine
#

what

supple thorn
#

not even discordpy

#

i use disnake

lucid vine
#

pycord?

#

oh

supple thorn
#

what's your get_prefix code

lucid vine
#
def get_prefix(client,message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

client = command.Bot(command_prefix= get_prefix, intents=intents)```
slate swan
#

how can I make an error handler specifically for CommandInvokeError

#
@plb.error
async def plb_error(ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        await ctx.send("No users have points!")
#

is that incorrect?

lucid vine
#

Its not working

torn sail
cold sonnet
#

yeah it probably is because of this

lucid vine
#

The bot is intended to get verified

cold sonnet
#

it can't work without defining bot correctly

supple thorn
lucid vine
#

I made the bot not intended to get it verified

glacial willow
#

typing here is all u need to do to ping here right?

#

with bot

slate swan
lucid vine
# supple thorn jesus christ

Its a nsfw bot and i have a server thats growing like hundreds of members daily cuz of the server and the bot is just an addition to the community and i also thought why not be public for everyone

supple thorn
lucid vine
glacial willow
slate swan
cold sonnet
lucid vine
cold sonnet
#

what did u do

slate swan
#

wtf ppl are discussing lmfaoo

lucid vine
#

I changed the command to commands

#

Didnt help

cold sonnet
#

but not in command_prefix

#

right?

supple thorn
lucid vine
lucid vine
slate swan
#

lmfao (everything cool nwo lol)

slate swan
#

if possible

oak oar
torn sail
slate swan
#

if u wanna use db.. u can use free plan of mongodb

cold sonnet
#

do you have an error?

lucid vine
lucid vine
oak oar
torn sail
cold sonnet
lucid vine
supple thorn
slate swan
supple thorn
torn sail
supple thorn
#

why do you have client

oak oar
slate swan
slate swan
supple thorn
#

that's why

slate swan
#

i just intent to tell ppl to not use json for that shit :'/

supple thorn
#

bruh

lucid vine
#

Confused

supple thorn
lucid vine
#

What difference does it make in 2.0

torn sail
slate swan
#

+1 ^

lucid vine
#

So no client

torn sail
#

Yes

supple thorn
#

why are you defining client twice?

lucid vine
#

Just use commands.Bot

torn sail
#

Yes

supple thorn
#

how the fuck did your old code work

slate swan
#

yt moment

#

:'/

oak oar
lucid vine
supple thorn
#

even if you downgraded back to default dpy version

#

it shouldn't work

lucid vine
#

and what do i do with the prefix

lucid vine
lucid vine
#

Im testing the bot on a different application and the main bot is running on my pi with the default version

supple thorn
lucid vine
twilit flame
#

πŸ˜‚

torn sail
#

You need to set intents.message_content to True

oak oar
#

if the code works don't touch it

  • some random guy
lucid vine
#

So yh what do i do with

twilit flame
#

are you trying to do a prefix for every server or a prefix by default?

lucid vine
#

Its already in like 40

torn sail
#

Should use bot vars and only open file on start and close

slate swan
#

😭 that's why i'm telling to not use json for that

lucid vine
#

Shouldnt this be enough

torn sail
#

messages is not message_content

oak oar
#

everyone is trying to help demon but it ain't working rooSob

lucid vine
#

I sincerly apologize and appriciate your love and help.

slate swan
#

btw which lib you're using? @lucid vine

slate swan
#

ah..no idea about how they're handling that..

#

sowwy, i'm of no help here ;'/

lucid vine
#
intents = discord.Intents(message_content=True, messages=True, guilds=True)
commands.Bot = discord.Client(intents=intents, command_prefix= get_prefix)
# ================================================================================================================

def get_prefix(client,message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

client = command.Bot(command_prefix= get_prefix, intents=intents)```
so i know i did something wrong
#

Just not sure what

supple thorn
torn sail
#

Remove commands.Bot = discord.Client

lucid vine
slate swan
#

πŸ’€ ai?

lucid vine
lucid vine
slate swan
#

πŸ’€ i thought u talking about copilot lmfao

twilit flame
torn sail
#

No no no no

#

Json opening every command is bad

slate swan
#

and he using json for that shit..

#

that's why i told him to not use json for that shit

twilit flame
slate swan
#

lmfaooo

lucid vine
#
intents = discord.Intents(message_content=True, messages=True, guilds=True)
# ================================================================================================================

def get_prefix(client,message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

client = command.Bot(intents=intents, command_prefix= get_prefix)```
lucid vine
oak oar
#

πŸ’€

lucid vine
#

Fuk i forgot the commands

slate swan
oak oar
slate swan
#

bie

twilit flame
#

damn

lucid vine
torn sail
#

Json is a data serialization format, that turns primitive data structures into a string.
A database is a formalized system designed to store and retrieve data, with a substantial
number of features and functionalities designed to support doing so at various scales,
and with a large number of guarantees.
A Json file as-a-db* is fundamentally flawed due to its lack of atomic writes
which results in data corruption and loss when:
β€’ The disk runs out of storage
β€’ The program crashes during the write
β€’ The computer crashes during write
β€’ Two programs try to write to the file at the same time
Additionally:
β€£ All reads require the entire file to be read
β€£ All reads require the entire structure to be loaded into memory *this does make it fast!
β€£ All writes require the entire file to be re-written
The Json module makes no effort to ameliorate any of these concerns, because json-as-a-db falls
completely and entirely out of the scope of the standard.
If you need the file to be portable and want minimum setup, use sqlite, a standard designed to
solve all these issues.
*Using the json stdlib module

slate swan
#

it is used for configuration not to be used as a db

lucid vine
torn sail
lucid vine
torn sail
#

Did u enable intents in dev portal

lucid vine
#

Yea

#

All 3

slate swan
#

u aren't getting any error even you're running the file? πŸ’€

lucid vine
#

Just double checked

twilit flame
#

why not use FASTAPI aswell 🀣

slate swan
#

bruhh

torn sail
#

Can u maybe show more code

slate swan
#

^

lucid vine
torn sail
#

!paste or a whole file

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.

lucid vine
#

Yh i can give u a snippet 2 sec

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @lucid vine until <t:1649310216:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 112 newlines in 10s).

slate swan
#

😐

supple thorn
#

lmao

slate swan
#

LMFAOOO

torn sail
#

Lol

slate swan
#

hey mod, pls unmute him

supple thorn
torn sail
wicked ivy
#

lol my bad

#

there

#

@torn sail

torn sail
#

Ok so loading extensions needs to be awaited

#

Also u shouldn’t change status so often

wicked ivy
#

why

#

ban?

#

should i increase the sleep interval?

torn sail
#

Probably

wicked ivy
#

on a sb i would understand but on a bot?

torn sail
#

Ok so you should make an async function named setup_hook where u load extensions. Then do client.setup_hook = setup_hook. Make sure to await loading extensions

wicked ivy
#

ohh ur talking about the cogs??

#

rn im not using the cogs anyways

torn sail
#

Oh

wicked ivy
#

its messy code

torn sail
#

Well ur also not running the bot

wicked ivy
#

what

#

oh i am

torn sail
#

Oh ok

wicked ivy
#

didnt send full code

torn sail
#

Send more?

#

I haven’t seen anything yet

wicked ivy
#

yh 2 sec

#

1 time view link so yh

torn sail
#

Page not found

wicked ivy
#

wat

#

lemme just send in dms

torn sail
#

Ok

little ivy
#

what do i need to type in my terminal to be able to use attribute "create_Text_channel ?

wicked ivy
#

wtf timeout is finished but im still muted

glacial willow
#

is ctx.author in a slash command the bot or the user who ran the command?

little ivy
#

Why do the ( & [ end up getting the error for not being closed?

cosmic agate
#

how to use twitch api?

azure scroll
#
@bot.command()
async def stopwatch(ctx, status : int):
  hours = 0
  minutes = 0
  seconds = 0
  
  if status == 1:
    await ctx.send("Started")
    while True:
      time.sleep(1)
      seconds += 1
    
      if (seconds == 60):
        seconds = 0
        minutes += 1

      if (minutes == 60):
        minutes = 0
        hours += 1

      if (hours == 24):
        hours = 0
        minutes = 0
        seconds = 0
        break
      elif status == 0:
        break
  elif status == 0:
    await ctx.send("Stopped")

I get no error but the bot doesn't send a message when i stop

supple thorn
#

also that's really bad to do cause that is blocking

#

pretty much making your entire bot seize up until it finishes that code

azure scroll
minor totem
supple thorn
little ivy
#

Why is this thing saying the ( is not closed?

supple thorn
little ivy
#

thats not my question

azure scroll
lucid vine
#
  File "C:\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
    from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Python310\lib\site-packages\discord\__init__.py)
supple thorn
minor totem
little ivy
supple thorn
minor totem
# azure scroll its a stopwatch

You should use asyncio.sleep() for the whole duration. Do you want it to send a message every now and then about the remaining time?

lucid vine
lucid vine
boreal ravine
supple thorn
#

πŸ—Ώ

azure scroll
lucid vine
minor totem
# lucid vine Wym

CokeCane is correct, you want to import it from discord.ext.commands: ```python
from discord import PartialEmoji, Emoji
from discord.ext.commands import InvalidArgument

supple thorn
boreal ravine
minor totem
supple thorn
#

i'm looking at the docs

supple thorn
#

i don't see invalidargument from commands

lucid vine
slate swan
#

hi is the python bot open source ?

lucid vine
#

In embeds

supple thorn
slate swan
#

!github

supple thorn
#

!source

unkempt canyonBOT
slate swan
#

ohh thnx

#

what library are you guys using for bot devlopment ?

minor totem
boreal ravine
minor totem
supple thorn
boreal ravine
boreal ravine
supple thorn
#

didn't it migrate back

boreal ravine
supple thorn
#

yeah i looked at it's src couple days ago

lucid vine
lucid vine
slate swan
minor totem
minor totem
heavy folio
heavy folio
slate swan
#

have you guys used hikari.py for making bots ?

heavy folio
#

nope but i would try it out soon

slate swan
boreal ravine
slate swan
#

BTW do you guys have any ideas what is the rest api and gateway version of discord currently ?

boreal ravine
lucid vine
# boreal ravine maybe looking at https://github.com/Rapptz/discord.py/blob/master/examples/views...
Ignoring exception in command colour:
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 192, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Yuki\Desktop\KyuuMainPy\r34bot\main.py", line 556, in colour
    await ctx.send.embedhelp(view=view)
AttributeError: 'function' object has no attribute 'embedhelp'

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

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 932, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 201, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'embedhelp'

error

embedhelp = discord.Embed(title="Mommy's Help Menu", color=0xff80ff)
embedhelp.add_field(name="'r34 [tags]'", value="**NSFW** Polls rule34 accordingly to your tags.", inline=False)
embedhelp.add_field(name="'prefix'", value="Changes your GUILDS set Prefix for Mommy", inline=False)    
embedhelp.add_field(name="'coin'", value="Flips a coin.", inline=False)
embedhelp.add_field(name="'kill'", value="Kills a User.", inline=False)
embedhelp.add_field(name="'hug'", value="Hugs a User.", inline=False)
embedhelp.add_field(name="'kiss'", value="Kisses a User.", inline=False)
embedhelp.add_field(name="'sex'", value="**NSFW** Makes out with a User.", inline=False)
embedhelp.add_field(name="'kick'", value="Kicks a User. : _kick @user", inline=False)
embedhelp.add_field(name="'ban'", value="Bans a User. : _ban @user", inline=False)
embedhelp.add_field(name="'mute'", value="Mutes a User: _mute @user.", inline=False)
embedhelp.add_field(name="'unmute'", value="Unmutes a Muted User. : _unmute @user", inline=False)
embedhelp.add_field(name="'tempmute / tm'", value="Temporarily Mutes a User : _tm @user 10s/d/w/mo/y tempmutereasonhere.", inline=False)
embedhelp.add_field(name="'userinfo'", value="Returns information about the User!", inline=False)
embedhelp.add_field(name="'serverinfo'", value="Returns information about the Server!", inline=False)
embedhelp.add_field(name="'rr'", value="**NSFW** Russian roulette. Posts gore images if gun goes off.", inline=False)
embedhelp.add_field(name="'shibe'", value="Posts an image of a Shiba inu.", inline=False)
embedhelp.add_field(name="'cat'", value="Posts an image of a cat.", inline=False)
embedhelp.add_field(name="'bird'", value="Posts an image of a bird.", inline=False)
class Dropdown(discord.ui.Select):
    def __init__(self):
        # Set the options that will be presented inside the dropdown
        options = [
            discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='πŸŸ₯'),
            discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
            discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦'),
        ]

        # The placeholder is what will be shown when no option is chosen
        # The min and max values indicate we can only pick one of the three options
        # The options parameter defines the dropdown options. We defined this above
        super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        # Use the interaction object to send a response message containing
        # the user's favourite colour or choice. The self object refers to the```
code
dull sorrel
#

How to send custom emojis?

#

The emoji is from the same server as the bot.

placid skiff
#

Morning guys

lucid vine
supple thorn
placid skiff
dull sorrel
supple thorn
#

i made a fiverr account

lucid vine
supple thorn
#

don't know what to do though

placid skiff
lucid vine
#

I over saw that

azure scroll
formal basin
#

Does all welcome commands need a db?

lucid vine
#
async def callback(self, interaction: discord.Interaction):
        # Use the interaction object to send a response message containing
        # the user's favourite colour or choice. The self object refers to the
        # Select object, and the values attribute gets a list of the user's
        # selected options. We only want the first one.
        await interaction.response.send_message(f'Your favourite colour is {self.values[0]}```

how do i set this to a custom embed depending on the interaction object?
#

Instead of the your favourite colour is ...

placid skiff
dull sorrel
lucid vine
vocal laurel
#

hey a question, how to make sub commands NOT case sensetive?

lucid vine
#

Use it like this to get the emoji id ect \ (emojihere), no space

lucid vine
lucid vine
#

Let me check

vocal laurel
#

k

lucid vine
#

!lower()

vocal laurel
#

ye but a sub command

boreal ravine
boreal ravine
boreal ravine
#

?

lucid vine
#

I see ty let me try

glass breach
#

1

lucid vine
#

The emojis have to be in the bots guild tho

vale wing
#

!d discord.Client.get_emoji

unkempt canyonBOT
#

get_emoji(id, /)```
Returns an emoji with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
vale wing
#

This is more correct method

lucid vine
#

Yea or that

#

@boreal ravinewhere did i indent wrong im confused

boreal ravine
#

you're not

lucid vine
#

Then what did i do wrong

boreal ravine
#

your just using tabs and spaces together and python doesn't like that

lucid vine
boreal ravine
#

πŸ€”

lucid vine
#

I cant run my code like this

vale wing
#

@lucid vine in vsc in the bottom right corner there's something that let's you convert code to tabs/spaces so you can quickly fix it

#

Typically pressing tab in VSC results in 4 spaces added as PEP8 states indents are recommended to be implemented with 4 spaces

#

If you didn't change the settings

lucid vine
#
class Dropdown(discord.ui.Select):
    def __init__(self):
        # Set the options that will be presented inside the dropdown
        options = [
            discord.SelectOption(label='NSFW', description='NSFW commands', emoji='πŸ”ž'),
            discord.SelectOption(label='Fun', description='Fun commands', emoji='😊'),
            discord.SelectOption(label='Mod', description='Moderation commands', emoji='πŸ”§'),
        ]

        # The placeholder is what will be shown when no option is chosen
        # The min and max values indicate we can only pick one of the three options
        # The options parameter defines the dropdown options. We defined this above
        super().__init__(placeholder='Pick your Category...', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        # Use the interaction object to send a response message containing
        # the user's favourite colour or choice. The self object refers to the
        # Select object, and the values attribute gets a list of the user's
        # selected options. We only want the first one.
        if self.values[0] == 'NSFW':
           await interaction.response.send_message(embed=embednsfw)
        elif self.values[0] == 'Mod':
           await interaction.response.send_message(embed=embedmod)
        elif self.values[0] == 'Fun':
           await interaction.response.send_message(embed=embedfun)



class DropdownView(discord.ui.View):
    def __init__(self):
        super().__init__()

        # Adds the dropdown to our view object.
        self.add_item(Dropdown())
        
@client.command()
async def colour(ctx):
    """Sends a message with our dropdown containing colours"""

    # Create the view containing our dropdown
    view = DropdownView()

    # Sending a message containing our view
    await ctx.send(embed = embedhelp,view=view)

how would i make this after ive selected the dropdown category the initial embed deletes itself

placid skiff
#

message = await ctx.send(embed = embedhelp, view=view)
when you want to delete it:
message.delete()

#

or you can even edit it:
message.edit(embed=a_new_embed)

lucid vine
lucid vine
#

So how would i make it that when the interaction response gets sent it gets deleted

#

Im confused

placid skiff
#

bro when you response to your interaction you send a new embed, right?

lucid vine
#

Yea

placid skiff
#

essentially you can do it in a lot of different ways:
saving the id of the message you want to delete, then use your interaction in the view to access that message and then delete it.
create a message parametere in your UI view and then you first send the message with the embed, then you create the view object, pass the message that you have sent, and then edit the message to add your view and then when the interaction is responded before sending the new embed delete the old one

#

is up to you

lucid vine
#

Can i just define the initial embed and then like add it to my if .... elif ... and delete it then?@placid skiff

#

Or wont it work like that

placid skiff
#

nope the embed is in the message, so you have to remove it from the message or delete the entire message

lucid vine
boreal ravine
#

await interaction.response.edit_message(embed=...)

lucid vine
#
class Dropdown(discord.ui.Select):
    def __init__(self):
        # Set the options that will be presented inside the dropdown
        options = [
            discord.SelectOption(label='NSFW', description='NSFW commands', emoji='πŸ”ž'),
            discord.SelectOption(label='Fun', description='Fun commands', emoji='😊'),
            discord.SelectOption(label='Mod', description='Moderation commands', emoji='πŸ”§'),
        ]

        # The placeholder is what will be shown when no option is chosen
        # The min and max values indicate we can only pick one of the three options
        # The options parameter defines the dropdown options. We defined this above
        super().__init__(placeholder='Pick your Category...', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        # Use the interaction object to send a response message containing
        # the user's favourite colour or choice. The self object refers to the
        # Select object, and the values attribute gets a list of the user's
        # selected options. We only want the first one.
        if self.values[0] == 'NSFW':
           await interaction.response.send_message(embed=embednsfw)
        elif self.values[0] == 'Mod':
           await interaction.response.send_message(embed=embedmod)
        elif self.values[0] == 'Fun':
           await interaction.response.send_message(embed=embedfun)



class DropdownView(discord.ui.View):
    def __init__(self):
        super().__init__()

        # Adds the dropdown to our view object.
        self.add_item(Dropdown())
        
@client.command()
async def help(ctx):
    """Sends a message with our dropdown containing colours"""

    # Create the view containing our dropdown
    view = DropdownView()

    # Sending a message containing our view
    await ctx.send(embed = embedhelp,view=view)

lucid vine
boreal ravine
#

if you mean embedhelp then yes

lucid vine
#

Oh okay yh that helps

#

Tyy let me try

#

Perfectly works

scarlet sorrel
#

what form do i need to open an image in to use await client.user.edit(avatar=image)? i tried rb and r and image.read() but none of that works. this is my code:

with open(f'pfps/' + str(math.floor(random.uniform(1, 8))) + '.png', 'rb') as image:
  image.read()
  await client.user.edit(avatar=image)
tired hinge
#

hi! i am using async-praw for a discord bot as praw is blocking. does anybody know any help servers like this for it?

#

i am encountering an authentication error when my credentials are correct.

supple thorn
tired hinge
#

aw

supple thorn
#

But they do have a subreddit

#

r/redditdev

#

Try asking it there

tired hinge
#

understood, thank you

#

my question has been asked multiple times there.

#

lmao

#

i tried all those fixes, none of them seem to work

#

i'll just claim a help channel

brisk zodiac
#
@client.command()
async def clear(ctx, amount=1000):
    await ctx.channel.purge(limit=amount)
    await ctx.send('Successfully delete {amount} messages')
```How can i fix the `{amount}`? I want it to send a specific number
unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

brisk zodiac
slate swan
# brisk zodiac Oh thx

you should actually store the purge method in a variable and use the len function on it since purge returns a list of Message objects, it will tell you the number of messages deleted rather than simply using the amount set by the user who invoked the command

spring flax
#

Yeah,it can fail to delete messages so if you say it deleted what the user put in it's inaccurate or misleading

#

Consider typehinting amount to int also

maiden fable
#

!d discord.TextChannel.purge

fallen merlin
#

!e import random

def highlow(num, high):
counter = 0
computer_guess = random.randint(1, high + 1)
already_there = []

while computer_guess != num:
    if num not in range(1, high + 1):
        print("Dirty bastard... I know what you've done. You cannot fool this machine.")
        break
    
    already_there.append(computer_guess)
    if computer_guess not in already_there:
        counter += 1
        computer_guess = random.randint(1, high + 1)
        print("A.I is computing", computer_guess)
        print("... \n ... \n ...")

if computer_guess == num:
    counter += 1
    print("Algorithim correct! I will rule mankind! It only took", counter, "tries!")

highlow(12, 12)

#

!e import random

def highlow(num, high):
counter = 0
computer_guess = random.randint(1, high + 1)
already_there = []

while computer_guess != num:
    if num not in range(1, high + 1):
        print("Dirty bastard... I know what you've done. You cannot fool this machine.")
        break
    
    counter += 1
    computer_guess = random.randint(1, high + 1)
    print("A.I is computing", computer_guess)
    print("... \n ... \n ...")

if computer_guess == num:
    counter += 1
    print("Algorithim correct! I will rule mankind! It only took", counter, "tries!")

highlow(12, 12)

unkempt canyonBOT
#

@fallen merlin :white_check_mark: Your eval job has completed with return code 0.

Algorithim correct! I will rule mankind! It only took 1 tries!
spice basalt
#

is there a way i can do this?

placid skiff
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
slate swan
fallen merlin
#

!e import random

def highlow(num, high):
counter = 0
computer_guess = random.randint(1, high + 1)
already_there = []

while computer_guess != num:
    if num not in range(1, high + 1):
        print("Dirty bastard... I know what you've done. You cannot fool this machine.")
        break
    
    counter += 1
    computer_guess = random.randint(1, high + 1)
    print("A.I is computing", computer_guess)
    print("... \n ... \n ...")

if computer_guess == num:
    counter += 1
    print("Algorithim correct! I will rule mankind! It only took", counter, "tries!")

highlow(12, 12)

unkempt canyonBOT
#

@fallen merlin :white_check_mark: Your eval job has completed with return code 0.

001 | A.I is computing 7
002 | ... 
003 |  ... 
004 |  ...
005 | A.I is computing 7
006 | ... 
007 |  ... 
008 |  ...
009 | A.I is computing 9
010 | ... 
011 |  ... 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/puyujuqeme.txt?noredirect

spice basalt
spice basalt
fallen merlin
slate swan
gilded gust
slate swan
spice basalt
#

if i were to embed these all, will that method still work?

gilded gust
#

very messy code here

spice basalt
supple thorn
spice basalt
#

yes

slate swan
spice basalt
little ivy
#

Hi guys

#

How do i make sure it prints when an option is chosen in the dropdown?

steady ember
#

Is there any alertnative for in method to send message faster via discord webhooks!

supple thorn
steady ember