#discord-bots

1 messages · Page 813 of 1

pallid mango
#

how do i put a space between the two "Server Restarted by Feyhe#6969 at 21:07!"?

sage otter
#

Using a line break

#

\n

pallid mango
#

where would i add it?

#

because it doesnt work if i add it in footer

pallid mango
dire folio
#

Oh

pallid mango
#

if i were to delete the first one itll get rid of all line breaks

final iron
sage otter
#

You can

pallid mango
#

okay so how do i blank a footer?

dire folio
#

Use an invis char

final iron
vale wing
#

Have you ever seen multiline footer

pallid mango
#

nopw

slate swan
#

Hey guys nextcord isnt doing what I want.

import nextcord
import asyncio
from nextcord.ext import commands
import os

intents = nextcord.Intents.all()
intents.members = True

client = commands.Bot(command_prefix="-", intents=intents)
client.remove_command("help")

@client.event
async def on_ready():
    await client.change_presence(
        activity=nextcord.Activity(type=nextcord.ActivityType.playing,name=f"Flanba Utilities2"))
    print("Client Ready")
mainguild = (932641118682767431)

@client.slash_command(guild_ids=[mainguild])
async def calculate(interaction: nextcord.Interaction):
  await interaction.response.send_message("In development")```

The slash command is not working, and no errors show up. What should I do?
vale wing
sage otter
#

It’s probably a lot more than 1k tbh

pallid mango
#

well, lets test

#

value=f"\n test",

slate swan
pallid mango
#

works

#

but at what cost !!!

slate swan
#

lol

pallid mango
slate swan
#

🤷

pallid mango
#

oh i know !!! blank character instead of the K

slate swan
pallid mango
#

and it all works perfectly

slate swan
slate swan
#

i made sure the guild id existed and was for the right server

#

like in the slash menu

vale wing
pallid mango
#

does anyone know how to configure the import time?

final iron
slate swan
sage otter
#

Like I said. The character limit is in the thousands. They wouldn’t spam it across your screen with not going doing go a new line.

vale wing
slate swan
#

as of right now, i just transfered to nextcord

#

due to py being discountinued anyways

pallid mango
slate swan
final iron
vale wing
pallid mango
#

kill the bot and itll unblock ur api

sage otter
slate swan
#

i doint think i did that actually

vale wing
#

@slate swan does the commands.Bot have test_guilds param? If so, provide your guild ID to there instead of the command

slate swan
#

i think i only used the normal bot scope

vale wing
#

There should be alternatives in other libs

final iron
#

There is a guild_ids kwarg

vale wing
#

!d nextcord.ext.commands.Bot

unkempt canyonBOT
#

class nextcord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`nextcord.Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") and as a result anything that you can do with a [`nextcord.Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.GroupMixin "nextcord.ext.commands.GroupMixin") to provide the functionality to manage commands.
slate swan
#

gotcha

vale wing
#

Ok haven't found anything

slate swan
#

like there isnt a guild_ids kwarg?

vale wing
#

I didn't see

final iron
rocky trench
#

Alright guys: I'm experiencing this issue: I use ctx.guild.voice_client.play, it says nonetype has no attribute play. I use the exact same thing in another check In another command, where it does work.

#

What could be the reason of it not working?

vale wing
#

Again? sillySmile

rocky trench
#
        ctx.guild.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(
            executable=f"C:/Users/bert/OneDrive - DvM Humaniora/Documenten/ShareX/Tools/ffmpeg.exe", source=url)),
            after=lambda error: self.bot.loop.create_task(self.play_next_song(ctx)))```Traceback (most recent call last):
  File "c:\Users\bert\Downloads\discord bots\Bertie's discord bots\cogs\slashes.py", line 760, in play_next_song
    await self.play_song(ctx, self.bot.song_queue[ctx.guild.id]["urls"][0])
  File "c:\Users\bert\Downloads\discord bots\Bertie's discord bots\cogs\slashes.py", line 786, in play_song
    ctx.guild.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(
AttributeError: 'NoneType' object has no attribute 'play'
pallid mango
#

hmm

vale wing
#

voice_client is a VoiceProtocol in your case and it doesn't have attribute play, but seems like in this case it doesn't even exist

pallid mango
#

seems like youtube_dl

rocky trench
#

But the ctx.guild.voice_client works in another command

rocky trench
pallid mango
#

oh

rocky trench
#

Just testing things out

pallid mango
#

ahh

vale wing
#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
vale wing
unkempt canyonBOT
#
Out of the question.

No documentation found for the requested symbol.

stray solar
#

someone know how to automatically delete message sent by a specific user (Command like: +autodelete {id}) (So when he sent a message like "i love apple" the message will be auto delete by the bot)

vale wing
#

What version of lib do you have

rocky trench
#

The thing is: if I use the join command, then play it doesn't work with the mentioned error above. If I use play command only (which has auto join if not joined already) it does work

#

Which uses the exactly same function

sick birch
#

Alternatively, give them a role that prevents them from talking altogether

vale wing
#

@rocky trench could you please tell what version of dpy do you have

rocky trench
#

And also I use slash_util in this command since it's a slash command

stray solar
#

i mean to make the command and the on_message

rocky trench
sick birch
#
on_message:
  if author.id in list_of_ids:
    message.delete()
  process_commands()

@stray solar

rocky trench
stray solar
#

uhh i dont get it but ok

rocky trench
#

On message event

#

Fetch the ids from database

#

If Id in database: message.delete

sick birch
#

Could've have phrased it better myself

rocky trench
#

I don't see why he doesn't get yours, it's pretty good ngl

sick birch
#

It boils down to a 3 step procedure really, pretty simple

stray solar
#

ok nvm just need to sleep lol

rocky trench
#

Yh

#

Gn!

stray solar
#

but first i have to end this command

sick birch
#

Your brain works better when it's rested, come back tomorrow and I guarantee you'll get it

stray solar
#

and i will sleep '-'

vale wing
rocky trench
#

if ctx.guild.voice_client:
if ctx.guild.me.voice.channel != ctx.author.voice.channel:
return await ctx.reply("You must be in the voicechannel the bot is in to play or add music!")
else:
await ctx.author.voice.channel.connect()

vale wing
#

O

rocky trench
#

Line 19

#

It doesn't reconnect, so it sees that bot is in a vc there

#

The error gets caused in the play song function when I use song --> play

#

Play only --> works

vale wing
#

So a quick explanation that might resolve your issue
There are 2 types of voice connection objects - VoiceState and VoiceProtocol. I don't get the point of VoiceProtocol but for some reason now it's everywhere and completely useless.

The only method that returns VoiceState is VoiceChannel.connect. So you have to store it in some variable to work properly. The VoiceProtocol doesn't have its methods and attributes

#

!d discord.VoiceState

unkempt canyonBOT
vale wing
#

!d discord.VoiceProtocol

unkempt canyonBOT
#

class discord.VoiceProtocol(client, channel)```
A class that represents the Discord voice protocol.

This is an abstract class. The library provides a concrete implementation under [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient").

This class allows you to implement a protocol to allow for an external method of sending voice, such as [Lavalink](https://github.com/freyacodes/Lavalink) or a native library implementation.

These classes are passed to [`abc.Connectable.connect`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").
rocky trench
#

@vale wing got an example of storing it in variable?

#

I mean I could give it a variable, but not be able to call it without making it global (which they didn't recommend)

vale wing
#

Well seems like the only option is a global variable but you could do a little trick - parse it instead of error arg in play function and make sort of recursion

stray solar
rocky trench
stray solar
#

i think im wrong

rocky trench
#

It works for my play command, but not for join + play

#

Which is impossible

vale wing
#

Well that's confusing

rocky trench
#

Yes indeed

stray solar
#

Bertie sorry but can u just help me for a sec

#
async def trigger(ctx, message, author):
    await ctx.message.delete
    if author.id in list_of_ids:
        message.delete()
    await client.process_commands()```
#

so now i made this but

rocky trench
#

Error?

#

Where do u define list_of_ids

stray solar
#

no no just how i can add id on the list

rocky trench
#

List.append id

slim ibex
#

append() ?

stray solar
#

um on the top i made 'list_of_ids = [,]'

rocky trench
#

What's the , for

stray solar
#

ups

rocky trench
#

(Should be in a command)

#

To add someone's id to the list

vale wing
#

@rocky trench personally I created a custom class that contained the voice state and the data required for playing songs, and put those to global queue variable which was storing list of those

rocky trench
#

(Also, a list is saved until you restart

rocky trench
#

A little too complicated for me to understand atm

stray solar
rocky trench
#

No

stray solar
#

ah the another one

rocky trench
#

U need to make a command where u append the id to that list

stray solar
#

i can put it on the same command ?

#
async def trigger(ctx, message, author, member):
    await ctx.message.delete
    list_of_ids.append(member.id)
    if author.id in list_of_ids:
        message.delete()
    await client.process_commands()```
#

like this

sick birch
#

That only works when someone runs the trigger command

vale wing
#

@rocky trench so basically this is the runner

 
 ​    ​@​staticmethod 
 ​    ​def​ ​play_next_track​(​_​=​None​): 
 ​        ​global​ ​now_playing 
 ​        ​if​ ​len​(​queue​) ​>​ ​0​:  
 ​            ​track​ ​=​ ​queue​[​0​] 
 ​            ​queue​.​remove​(​track​) 
 ​            ​now_playing​ ​=​ ​track 
 ​            ​track​.​vc​.​play​(​disnake​.​FFmpegPCMAudio​(​track​.​url​, ​executable​=​'ffmpeg'​, ​**​Music​.​FFMPEG_OPTIONS​),  
 ​            ​after​=​Music​.​play_next_track​)```
sick birch
#

You want all messages to be deleted, yes?

vale wing
#

Stupid github indents

sick birch
#

then use on_message

stray solar
#

I want when the user sent a message, the bot automatically delete the message

rocky trench
vale wing
#

Sry for those

stray solar
#

but i want to put it on command

rocky trench
#

It recognizes the voice channel when I use the autojoin inside the play command, but not when I use join command and play command

stray solar
#

or maybe the command trigger gonna ad the id to the list and on message will delete his msg

sick birch
sick birch
#

But if they say anything else, it won't be deleted

stray solar
#

if i do +trigger {id}

rocky trench
#

Is it your birthday today Robin?

stray solar
#

any message the user will send its will be delete

sick birch
sick birch
rocky trench
stray solar
#

ok so imma just do a command for a the id to the list, and on_message will just trigger the user

rocky trench
sick birch
stray solar
sick birch
#
def add():
  # add user to database
def on_message():
  # if message author is in database, delete
stray solar
#

ok so i do

#
async def triggerlist(ctx):
    await ctx.message.delete()
    ``` that first
#

or i get wrong xd

rocky trench
#

Nono

#

Robin, I think u understand him wrong

sick birch
#

I don't think you get what those do, if it has @bot.command(), that means whenever your bot sees a message like <prefix><command name>, everything inside will get executed

rocky trench
#

Triggerlist is to add an Id the the list, and he uses that id to delete all messages

stray solar
#

(im sorry im rly rly bad so its hard for me xd to make the command alone..)

sick birch
#

ah

#

that makes more sense

stray solar
#

aaaaaaaaaaaaa

sick birch
#

so you want to do:

<prefix>triggerlist <id>
#

that would add a user to the trigger list?

stray solar
#

yea and the on_message will made the trigger

rocky trench
#

Will delete all messages from the ids in the list

stray solar
#

delete any message he sent*

sick birch
#

Oh yeah that should be relatively easy

stray solar
#

like now (watch)

sick birch
#

hardest part would be getting the database

stray solar
#

and its done xd

rocky trench
stray solar
#

i use 1 file XD

#

1021 lines

#

and just .bat file xd

#

so the data base its will be hard y

sick birch
rocky trench
#

Yh indeed

#

I wouldn't learn databases to a (beginner) not to be rude

sick birch
stray solar
#

im a real beginner dont worry xd

rocky trench
#

I mean u could try it...

stray solar
#

(i try every command.. its just this one im lost)

#

i made blacklist and whitelist but trigger..

sick birch
#

The way I did it, I have an express.js server with either TypeORM or prisma or some other orm, and inside python, instead of messing with like motors or connectors like aiosqlite, you just use aiohttp and send a request to the API server

stray solar
#

oh sh...

sick birch
#

but you don't have to do that, you can go with the traditional approach if you'd like

stray solar
#

yeaaa i like traditional

#

ok so now, we get the logic, just something to do its the command to add list and AFTER do the on_message..

#

so the hardest part.. why sometimes i hate me

flat solstice
#

somethings not quite right with this command. It executes all the way through without any error's and sends me a dm saying it's searched 50k msgs when it finishes but it isn't posting any embeds, I have just noticed that the messages it s searching through are all webhooks so should I be accounting for that```py
@commands.command()
@commands.has_permissions(administrator = True)
async def moderation_logs(self, ctx):
snowyjaguar = self.bot.get_user(self.bot.config.owner)
checked_logs = []
case_count = 0
last_checked = 0
moderation = await self.bot.fetch_channel(885569667861717042)
clifford_log = await self.bot.fetch_channel(500768218257031168)
# Field One: User who was moderated *
# Field Two: Moderator who performed the moderation *
# Field Three: Reason for moderation
# Field Four: Duration of moderation

    with moderation.typing():
        messages = await clifford_log.history(oldest_first = True, limit = None, after = last_checked).flatten() # 10000
        for message in messages[0:]: # Making bot search history chronologically
            if all([
                message.id not in checked_logs, 
                message.author.id == 776782769312628746, 
                len(message.embeds) > 0, 
            ]):
                #action = [word for word in key_words if word in message.embeds[0].title]
                #if len(action) > 0:
                if action := [word for word in self.bot.config.key_words if word in message.embeds[0].title]:
                    embed = discord.Embed(title = f"Case {case_count} | {action[0]}", colour = self.bot.config.error_colour, timestamp = message.timestamp)
                    embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url)
                    embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url})
                    embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True)
                    embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True)
                    if message.embeds[0].fields[3]:
                        embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value)
                    if message.embeds[0].fields[2]:
                        embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value)
                    checked_logs.append(message.id)

                    await moderation.send(embed = embed)
        await snowyjaguar.send(f"`{len(messages)}` were checked in {clifford_log.mention}, `{case_count}` logs were logged in {moderation.mention}")```
stray solar
#

oh ok its logs hmm

vale wing
stray solar
#

honnestly i put my logs on console bot so i cant help u sry

flat solstice
magic harbor
#

uhh guys

#

i need to make a bot that would ping a role after a certain time, and it will read a message from another bot to determine the time after which it needs to ping. any pointers on where to start? i am pretty new to python. also can i host the bot on repl?

stray solar
#

@sick birchi got an idea for the triggerlist, imma take my command blacklist and just change some things to add on my triggerlist

final iron
magic harbor
final iron
sick birch
stray solar
#

'sounds' xd

final iron
#

Github developer pack or whatever its called is also an option

stray solar
#

ok im lost

final iron
#

You get a ton of free hosting iirc

magic harbor
#

also idk how to make it ping roles. what do i need to import to make it do that?

magic harbor
final iron
#

!d discord.Role.mention

unkempt canyonBOT
final iron
#

You can mention it with this

#

You will need an instance of the Role class

#

Have you learnt oop yet?

magic harbor
#

i can make basic functions🥲

final iron
#

objects, classes and such

magic harbor
#

ok so i need to import discord first for those commands?

dire folio
final iron
#

To sign up, yes

#

They charge like 0.01 to see if the card is valid

magic harbor
#

rip, i don't have one. i am a minor so...

stray solar
#

@sick birch um... discord.ext.commands.errors.MissingRequiredArgument: author is a required argument that is missing.

#

something wrong...

dire folio
#

That's what AWS do too isn't it?

final iron
#

I got my debit card when I was 9

stray solar
#

yea but idk why

dire folio
#

When u typed the cmd

#

Into disc

magic harbor
slate swan
#
@ban.error

AttributeError: 'function'  object has no attribute 'error'
#

Why?

final iron
magic harbor
#

ooo ok

final iron
#

You just need proof you're in school

#

A report card, student id, literally anything will work

stray solar
#

+trigger <id>@dire folio

magic harbor
final iron
#

I just used my id

magic harbor
#

ok

final iron
#

You need a picture of your id and a picture of yourself iirc

magic harbor
#

imma go and import discord.py first and then i can think about the commands

final iron
#

Sure

magic harbor
#

tyyy

final iron
#

Extremely well made tutorial. Teaches good practices and such

magic harbor
#

wow tyyy

final iron
#

It doesn't entirely follow pep8 but its fine

slate swan
#

Ok

#

@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingAnyRole):
        emb=discord.Embed(title="❌ Error", description="**__Информация:__**", color=discord.Color.from_rgb(255, 0, 0), timestamp=ctx.message.created_at)
        emb.set_footer(text="© Все права защищены The Greatest", icon_url=ctx.author.avatar_url)
        emb.set_thumbnail(url = ctx.author.avatar_url)
        emb.add_field(name="**У вас недостаточно прав.\nУчастник, который ввел команду:**", value=f"**{ctx.author.name}**", inline=False)
        await ctx.reply(embed=emb)
#

@stray solar

dire folio
final iron
#

Report card

#

Literally any form of identification

dire folio
#

I'm guessing the identification needs ur face on it?

final iron
#

¯_(ツ)_/¯

stray solar
slate swan
final iron
stray solar
#

and not use an isinstance

dire folio
#

If they need the face my report card doesn't have it

stray solar
#

like this:

final iron
#

But it wouldn't hurt to try

#

You get so much free shit

dire folio
#

I'll try that

final iron
stray solar
#

im making wait

slate swan
#

🤔

stray solar
#

u rly want to use embed ? for ur ban command

slate swan
#

Everything worked in @kick.error, but not in ban

stray solar
#



    except Exception as e:
        await ctx.send.embed(embed={e})
#

something like this

stray solar
#

if its was working on @hot crow.error maybe u copied too fast or something xd

#

UPS

#

i pinged someone fk

slate swan
#

Okay

stray solar
#

and if its still not working u can use the except exception as e

#

u have to put ur ban command after try:

slim ibex
#

why not put the exact error in the except

stray solar
#

{e} will send the current error

slim ibex
#

ik

stray solar
#

like require argument or something

#

and thats it xd

slim ibex
#

You can handle that stuff in on_command_error

#

You won’t have to have a @command.error everywhere

stray solar
#

y, just for my part i use this like that

#

i just made the command, and put the except

slim ibex
#

ehh whatever works I guess

stray solar
#

like this and its finish xd

#

simple and faster

slim ibex
#

ctx.send.embed?

stray solar
#

ups thats my little tips

slate swan
#
@ban.error

AttributeError: 'function'  object has no attribute 'error'
stray solar
#

ah !

slim ibex
#

the function name has to be ban

slate swan
#

🤔

stray solar
#

ah ?

#

so idk

slate swan
#

(

slim ibex
#
@command()
async def ban():
    ….

@ban.error

You see how the function name of the ban command is the same as what is before .error

slate swan
#

🤔

dire folio
#

How do I make a command execute on a specific date

slate swan
#

Everything worked in @kick.error, but not in ban

stray solar
#

datetime ?

rocky trench
#

Send ur full code wzr

stray solar
rocky trench
#

The ban command + the error code

stray solar
#

bcs i was done to dont know how to made the full comand so well..

#

rip me

rocky trench
slate swan
#

Everything is already working

pliant nacelle
#
    async def setup(self, ctx):
        conn = sqlite3.connect('voice.db')
        c = conn.cursor()
        guildID = ctx.guild.id
        id = ctx.author.id
        if ctx.author.id == ctx.guild.owner.id or ctx.author.id == 788926833801691177:
            def check(m):
                return m.author.id == ctx.author.id
            await ctx.channel.send("**You have 60 seconds to answer each question!**")
            await ctx.channel.send(f"**Enter the name of the category you wish to create the channels in:(e.g Voice Channels)**")
            try:
                category = await self.bot.wait_for('message', check=check, timeout = 60.0)
            except asyncio.TimeoutError:
                await ctx.channel.send('Took too long to answer!')
            else:
                new_cat = await ctx.guild.create_category_channel(category.content)
                await ctx.channel.send('**Enter the name of the voice channel: (e.g Join To Create)**')
                try:
                    channel = await self.bot.wait_for('message', check=check, timeout = 60.0)
                except asyncio.TimeoutError:
                    await ctx.channel.send('Took too long to answer!')
                else:
                    try:
                        channel = await ctx.guild.create_voice_channel(channel.content, category=new_cat)
                        c.execute("SELECT * FROM guild WHERE guildID = ? AND ownerID=?", (guildID, id))
                        voice=c.fetchone()
                        if voice is None:
                            c.execute ("INSERT INTO guild VALUES (?, ?, ?, ?)",(guildID,id,channel.id,new_cat.id))
                        else:
                            c.execute ("UPDATE guild SET guildID = ?, ownerID = ?, voiceChannelID = ?, voiceCategoryID = ? WHERE guildID = ?",(guildID,id,channel.id,new_cat.id, guildID))
                        await ctx.channel.send("**You are all setup and ready to go!**")
                    except:
                        await ctx.channel.send("You didn't enter the names properly.\nUse `.vc setup` again!")
        else:
            await ctx.channel.send(f"{ctx.author.mention} only the owner of the server can setup the bot!")
        conn.commit()
        conn.close()
#

get this error

#
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "setup" is not found

#

when i do .setup

magic harbor
#

how to post code here?

pliant nacelle
#

what

pliant nacelle
magic harbor
#

!paste

#

👀 🥲

pliant nacelle
bold surge
#

use a pastebin pls

magic harbor
pliant nacelle
#

test

magic harbor
bold surge
#

a site where you can paste your code and it returns a link to it so the chat isnt flooded with code

bold surge
#

if yes, can i see your decorators

magic harbor
#
from flask import Flask
from threading import Thread 
app = Flask('')

@app.route('/')

def main():
   return "Your Bot Is Ready"

def run(): 
  app.run(host="0.0.0.0", port=8000) 

def keep_alive():
  server = Thread(target=run) 
  server.start()

bot = commands.Bot(command_prefix="!")
@bot.command(name="hello")
async def hello_world(ctx: commands.Context):
    await ctx.send("Hello, world!")
    bot.run("token")

status = cycle(['with Python','JetHub']) 
@bot.event
async def on_ready():
   change_status.start() 
   print("Your bot is ready") 
   @tasks.loop(seconds=10)
   async def change_status():
      await bot.change_presence(activity=discord.Game(next(status)))
bold surge
bold surge
magic harbor
bold surge
#

yea you just have to import one file into another

pliant nacelle
magic harbor
bold surge
#

and it creates a webserver

#

but yes

magic harbor
#

tyyy

pliant nacelle
hoary cargo
pliant nacelle
#

i can't setup my bot

magic harbor
vague grove
#

hey guys, I compiled my music bot with pyinstaller and it keeps giving me the error Command raised an exception: OpusNotLoaded: what does this mean? it uses ffmpeg n stuff

quaint forum
#

@client.event is when the bot detects anything right

velvet tinsel
#

evening

velvet tinsel
#

events are specific....events

magic harbor
#

status = cycle(['with Python','JetHub'])

velvet tinsel
#

listen() is probably what you're looking for

magic harbor
#

said no dependency

#

🥲

quaint forum
quaint forum
velvet tinsel
#

the documentation

quaint forum
#

yeah i found it

magic harbor
visual island
#

!d typing.Optional

unkempt canyonBOT
#

typing.Optional```
Optional type.

`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:

```py
def foo(arg: int = 0) -> None:
    ...
```  On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example...
visual island
#

why not?

magic harbor
#
No dependencies to install or update
/home/runner/EPIC-BOT/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(``` replit giving this when i run the code
visual island
#

!e

def foo(b, a=1, *args): ...
foo(1)
``` this works
unkempt canyonBOT
#

@visual island :warning: Your eval job has completed with return code 0.

[No output]
slim ibex
#

*foo can’t have default arguments

visual island
#

ah

slim ibex
#

cuz it’s replit 🗿

visual island
#

you need commands.Greedy for it

#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

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

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

For example, in the following code:

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

it takes any number of argument with the specified type, but also skips if not given

slim ibex
#

you can import greedy

#

from discord.ext.commands import Greedy

#

So you don’t have the whole thing in the params

visual island
#

yeah that would do, but ^ is neater

quaint epoch
#

I have a task that i want my bot to do, constantly check a database, how do i do that?

torn sail
#

This has already been answered but an alternative is to type hint member to typing.Optional[discord.Member] if it can’t convert it to a member it will pass it to the next arguement

slate swan
#

Anyone knows where to find like a on_member_join_voicechannel on nextcord?

#

I cant find anything related to this in the api reference

#

im assuming nextcord calls it a client event

#

nvm found it lol

#

nextcord.on_voice_state_update

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AssertionError: 
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f9366031a90>```
#

i get this errori try to enter a website

#
    @commands.command(name="Role")
    async def role(self, ctx, member:discord.Member):
        await member.add_roles("Test")
#
Traceback (most recent call last):
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Ignoring exception in command Role:
Traceback (most recent call last):
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 448, in role
    await member.add_roles("Queer")
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'

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

Traceback (most recent call last):```
hard trail
#

I've been looking for a way to withdraw in a discord bot and I found one of swastiks old vids so i checked it out but the withdrawl wasn't working

async def withdraw(ctx,amount = None):
  await open_account(ctx.author)

  if amount == None:
    await ctx.reply("Add an Amount")
    return

  bal = await update_bank(ctx.author)

  amount = int(amount)
  if amount>bal[1]:
    await ctx.reply("You don't have that much money")
    return
  if amount<0:
    await ctx.reply("Add a Positve Amount")
    return
   
  await update_bank(ctx.author,amount)
  await update_bank(ctx.author,-1*amount,"bank")
  await ctx.reply(f"Successfully withdrew {amount} coins")




async def update_bank(user, change=0,mode="wallet"):
  users = await get_bank_data()

  users[str(user.id)][mode] += change

  with open("mainbank.json", "w") as f:
    json.dump(users,f,indent=4)

  bal = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]

  return bal```
#

Some reason it ain't working

slate swan
#
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AssertionError: 
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f9366031a90>```
#

i get this error when i want yo enter a websitewith aiohttp

patent lark
patent lark
patent lark
steel void
#
@CLIENT.slash_command(name = "restart", description = "Allows vondy to restart the bot.")
@commands.is_owner()
async def restart(ctx, seconds:float):
    em = discord.Embed(title = "OFF", description = f"Vondy turned me off for {round(seconds)} seconds", color = discord.Color.red())
    await ctx.send(embed = em)
    await CLIENT.close()
    sleep(seconds)
    await CLIENT.connect()
    em = discord.Embed(title = "Turned on", description = f"I came back after {round(seconds)}", color = discord.Color.green())
    await ctx.send(embed = em)```
why does the bot not reconnect?
#

pycord

slate swan
#
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AssertionError: 
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f9366031a90>```
#

i get this erro when

#

i try to use aiohttp

#

to enter a site

patent lark
#

do you get an error?

steel void
#

no error

patent lark
#

yeah, i dont think you can do that.

gaunt ice
#

can rhe botwatch my video when i turn it one

slate swan
#

hdelp?

gaunt ice
#

hm

left crater
steel void
#

hey i got two bots in the same container how can i use one bot to start the other

hard trail
slate swan
# steel void hey i got two bots in the same container how can i use one bot to start the othe...
import asyncio
import discord
from discord.ext import commands
loop = asyncio.get_event_loop()
mainbot = commands.Bot(loop=loop, command_prefix="!")
bot_one = commands.Bot(loop=loop, command_prefix="1>")
bot_two = commands.Bot(loop=loop, command_prefix="2>")
@mainbot.command()
async def ping1(ctx):
  await ctx.send("Pong. I'm main bot.")
@bot_one.command()
async def ping2(ctx):
  await ctx.send("Pong. I'm bot one.")
@bot_two.command()
async def ping3(ctx):
  await ctx.send("Pong. I'm bot two.")
loop.create_task(bot_one.start(bot1token))
loop.create_task(bot_two.start(bot2token))
mainbot.run(mainbottoken)
fervent shoal
#

@bot.listen()
async def on_message(message: discord.Message):
if message.author.bot: return
for i in ratio:

im tryna have it detect the gif and delete the message, how would i go about that from here

slate swan
fervent shoal
#

@bot.listen()
async def on_message(message: discord.Message):
if message.author.bot: return
for i in ratio:
message.delete
await ctx.send(f"{Member} don't send that gif")

#

its telling me ctx isnt defined

slate swan
#

how can i change this to accept image input instead of text?

    @commands.command(name="t")
    async def attach(self,ctx,member: discord.Member=None):
        if not member:
            member = ctx.author
        pfp = member.avatar_url
        guildicon = ctx.guild.icon_url
        memberroles = [role.name for role in member.roles]
        membermention = ctx.author.mention
        memberID = ctx.author.id
        questions = [
                "**Send an image:**",
                "**Random Placeholder:**",
        ]
        embed=discord.Embed(title=f"**Partner Finder**", description=f"verify bot test", color=0x80646B)
        embed.set_author(name="Roleplay Hub", icon_url=guildicon)
        dmChannel = await ctx.channel.send(embed=embed)
        def check(message):
            return message.author == ctx.author and message.channel == ctx.channel
        
        async def askQuestion(question):
            embed=discord.Embed(title=f"{question}", description=f"** **", color=0x80646B)
            embed.set_author(name="Roleplay Hub", icon_url=guildicon)
            await ctx.channel.send(embed=embed)
            next_step = True
            while next_step:
                userReply = await self.bot.wait_for('message', check=check)
                next_step = True
                print(f"RMV: Waiting for reply from {member}")
                return userReply.content
        verificationimage = await askQuestion(questions[0])
        verificationimage2 = await askQuestion(questions[1])
        print(f"{verificationimage}")
        embed=discord.Embed(title=f"**Verification Test**", description=f"**Discord User**: {membermention} | {member} ", color=0xFF0000)            
        embed.set_thumbnail(url=(pfp))
        embed.add_field(name="**Request Channel**:", value=f"{verificationimage}", inline=False)
        embed.set_footer(text="Roleplay Hub⠀⠀⠀Developed by r0yal#2029")
        await ctx.channel.send(embed=embed)
fervent shoal
#

so await message.send?

slate swan
#

right now it asks you a question, waits and captures your reply and then sends your reply into the embed at the bottom

slate swan
fervent shoal
#

Much thanks

opaque tiger
#

i am not using cogs... @placid skiff @final iron @honest vessel

slate swan
#

i've managed to do it seperately with

    @commands.command(name="t")
    async def attach(self, ctx):
        f = await ctx.message.attachments[0].to_file()
        embed = discord.Embed()
        embed.set_image(url=f"attachment://{f.filename}")
        await ctx.channel.send(file=f, embed=embed)```
#

but idk how to combine them properly

fervent shoal
#

@bot.listen()
async def on_message(message: discord.Message):
if message.author.bot: return
message.delete
await message.channel.send("Don't send that gif")

its not deleting the message now

opaque tiger
opaque tiger
fervent shoal
#

Thanks

slate swan
opaque tiger
opaque tiger
fervent shoal
#

Code is still reloadin, rby pi is slow lol

slate swan
#

im guessing this is the line i need to change but i don't know how to make it accept attachments / images


              userReply = await self.bot.wait_for('message', check=check)
#

the code u replied to works fine @slate swan

opaque tiger
fervent shoal
#

yep it worked, much thanks

slate swan
opaque tiger
slate swan
#

so the user is prompted to send an image, they send one and then that image is added inside the embed

#

the same way now that they're prompted to send text, they send it and then the text is added inside the embed

slate swan
#

im guessing i need to mess with this line


               userReply = await self.bot.wait_for('message', check=check)
#

but i don't know what to change it to for it to capture and accept images

gaunt ice
#

hm

#

can the bot watch the video of some user in a vc

slate swan
#

wdym

jade jolt
#

i assume he means if theyre screensharing

#

can the bot see what that user is showing?

#

idk, thats all i could get

slate swan
#

nah

#

maybe capture was the wrong word

jade jolt
#

does your line of code work

jade jolt
#

and what does your check look like? @slate swan

slate swan
#

this is what it does rn

#

it all works for text

#

i literally just have zero idea how to convert it to accept it for attachments

jade jolt
#

show me your check

#

i might be able to help

opaque tiger
slate swan
#
    @commands.command(name="t")
    async def attach(self,ctx,member: discord.Member=None):
        if not member:
            member = ctx.author
        pfp = member.avatar_url
        guildicon = ctx.guild.icon_url
        memberroles = [role.name for role in member.roles]
        membermention = ctx.author.mention
        memberID = ctx.author.id
        questions = [
                "**Send an image:**",
                "**Random Placeholder:**",
        ]
        embed=discord.Embed(title=f"**Partner Finder**", description=f"verify bot test", color=0x80646B)
        embed.set_author(name="Roleplay Hub", icon_url=guildicon)
        dmChannel = await ctx.channel.send(embed=embed)
        def check(message):
            return message.author == ctx.author and message.channel == ctx.channel
        
        async def askQuestion(question):
            embed=discord.Embed(title=f"{question}", description=f"** **", color=0x80646B)
            embed.set_author(name="Roleplay Hub", icon_url=guildicon)
            await ctx.channel.send(embed=embed)
            next_step = True
            while next_step:
                userReply = await self.bot.wait_for('message', check=check)
                next_step = True
                print(f"RMV: Waiting for reply from {member}")
                return userReply.content
        verificationimage = await askQuestion(questions[0])
        verificationimage2 = await askQuestion(questions[1])
        print(f"{verificationimage}")
        embed=discord.Embed(title=f"**Verification Test**", description=f"**Discord User**: {membermention} | {member} ", color=0xFF0000)            
        embed.set_thumbnail(url=(pfp))
        print("fanny2")
        embed.add_field(name="**Image**:", value=f"{verificationimage}", inline=False)
        embed.add_field(name="snip", value=f"{verificationimage2}", inline=False)
        embed.set_footer(text="Roleplay Hub⠀⠀⠀Developed by r0yal#2029")
        await ctx.channel.send(embed=embed)
#

here is the entire code

jade jolt
#

lets go in dm

slate swan
#

ok

opaque tiger
final iron
opaque tiger
slate swan
#

how can u check if a vc gets full in nextcord?

final iron
#

!d discord.VoiceChannel

unkempt canyonBOT
#

class discord.VoiceChannel```
Represents a Discord guild voice channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
final iron
unkempt canyonBOT
final iron
#

!d discord.VoiceChannel.user_limit

unkempt canyonBOT
final iron
#

There

#

You can do some simple arithmetic

cyan ermine
#

how to run a cog

final iron
unkempt canyonBOT
#

load_extension(name, *, package=None)```
Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
final iron
#

This channel died

slate swan
#

sad.

final iron
#

okimii is being annoying

#

I can't work on our api wrapper until he fixes an error

#

And hes offline

slate swan
#

async twitter client?

final iron
#

Yeah

#

Check my github

#

I have it forked

slate swan
#

sure

final iron
#

He just did a rewrite and docs are broken

#

anaconda is also being very weird for me and I don't know if its a weird issue with python or anaconda

pliant gulch
#

👁️👁️

final iron
#

Yes andy

#

Send help

slate swan
#

why people prefer anaconda? like does it have any additions to python ( i havent used it yet so idk)

final iron
#

idk

#

It was just the first thing I ever used

#

So I stuck with it

slate swan
#

i used anaconda once when i used spyder ide logo_spyder

final iron
#

It also has some built in libs that python doesn't have

#

Like aiohttp

#

And a lot more apparently

slate swan
#

which can be installed from pypi...

final iron
#

yeah ik

pliant gulch
#

You guys should've used httpx instead of aiohttp for your twitter thingy

final iron
#

Talk to okimii

#

Also, why?

#

!pypi httpx

unkempt canyonBOT
final iron
#

Andy have you ever used anaconda?

pliant gulch
#

No I have not

#

@slate swan ```py
from future import annotations

import rin

import asyncio
import os

token: str = os.environ["DISCORD_TOKEN"]
client = rin.GatewayClient(token, intents=rin.Intents.default())

@client.once(rin.Events.READY)
async def ready(user: rin.User) -> None:
print(f"Logged in as: {user.id}")

@client.on(rin.Events.MESSAGE_CREATE)
async def message_created(message: rin.Message) -> None:
print(f"Received a message! {message}")

@rin.AppCommand(rin.ChatCommand)
class HelloWorldCommand:
guilds = [907106240537169980]
description = "A demo description."
name = "hello"

@HelloWorldCommand.on()
async def callback(interaction: rin.Interaction) -> None:
await interaction.send(f"Hello {interaction.author}!")

asyncio.run(client.start())

grim oar
#

Nice

slate swan
pliant gulch
#

That can be done, the only thing the class actually does is act as metadata for the command before construction

#

On runtime the class itself is replaced by a rin.ChatCommand instance

#

The corresponding metadata in the class namespace would then be translated in there

frail mesa
#

Ok I am back. have made 0 progress on this command, cannot for the life of me figure out why it wont work. any help is appreciated. invokes no errors, sends the message "member successfully updated" but doesnt actually remove any roles

@bot.command()
@commands.has_role('Server Owners')
async def cleanup(ctx):
  big_airut_speedrun_1 = ctx.guild.get_role(826189814596108378)
  big_airut_speedrun_2 = ctx.guild.get_role(762488902304006174)
  big_airut_speedrun_3 = ctx.guild.get_role(757836549361762424)
  roles = ctx.guild.roles
  for member in ctx.guild.members:
    try:
      if any(role.id == big_airut_speedrun_1.id for role in roles):
        await member.remove_roles(big_airut_speedrun_2)
        await member.remove_roles(big_airut_speedrun_3)
        await ctx.channel.send('Member successfully updated.')
      elif any(role.id == big_airut_speedrun_2.id for role in roles):
        await member.remove_roles(big_airut_speedrun_3)
        await ctx.channel.send('Member successfully updated.')
      else:
        await ctx.channel.send('Command complete.')
    except HTTPException:
      print("something went bad")
slate swan
slate swan
slate swan
pliant gulch
slate swan
#

that would be great

pliant gulch
#

In this case, it would make the constructor huge. But you could also do @my_command.subcommand(...)

frail mesa
#

so how would i specify all roles of one member?

slate swan
#

member.roles

frail mesa
#

ok so changed the if statements to if any(member.roles == big_airut_speedrun_1):

slate swan
frail mesa
#

now am getting error 'bool' object is not iterable

slate swan
frail mesa
slate swan
#

you cant compare a role object with a list, simply use the in statement

#
if role in member.roles:
  ...```
frail mesa
#

oh gotcha, makes sense

#

ok so now i have

@bot.command()
@commands.has_role('Server Owners')
async def cleanup(ctx):
  big_airut_speedrun_1 = ctx.guild.get_role(826189814596108378)
  big_airut_speedrun_2 = ctx.guild.get_role(762488902304006174)
  big_airut_speedrun_3 = ctx.guild.get_role(757836549361762424)
  for member in ctx.guild.members:
    if big_airut_speedrun_1 in member.roles:
      await member.remove_roles(big_airut_speedrun_2)
      await member.remove_roles(big_airut_speedrun_3)
      await ctx.channel.send('Member successfully updated.')
    elif big_airut_speedrun_1 in member.roles:
      await member.remove_roles(big_airut_speedrun_3)
      await ctx.channel.send('Member successfully updated.')
    else:
      await ctx.channel.send('Command complete.')

the command runs, prints out "command complete" but doesnt actually remove any roles

#

also it is very fast, which makes me think its not actually going through every single member as it should ?

tiny ibex
#
@bot.command()
async def recognize(ctx, url = None):
    if url is None:
        if ctx.message.attachments is None:
            attachment = ctx.message.attachments[0]
            url = attachment.url
        else:```
#

Can someone tell why it doesn't work

#

??

frail mesa
#

idk what that means sorry 🙈

slate swan
#

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

frail mesa
#

i do not have that, no

slate swan
#

read what it says

frail mesa
#

yea, adding it now

#

hmm weird.

#

ok have to change some permissions in discord developer apparently. perhaps that was the issue

#

ok i have run it now and it keeps printing "command complete"

#

i think this means its working correctly? it should print that for every member, yea?

#

oh dear this is gonna take awhile

frail mesa
#

ok my god its actually working now

#

one other question, if anyone knows any solution? this is the current command now

@bot.command()
@commands.has_role('Server Owners')
async def cleanup(ctx):
  big_airut_speedrun_1 = ctx.guild.get_role(826189814596108378)
  big_airut_speedrun_2 = ctx.guild.get_role(762488902304006174)
  big_airut_speedrun_3 = ctx.guild.get_role(757836549361762424)
  count = 0
  count_message = await ctx.channel.send(f'{count} members updated.')
  for member in ctx.guild.members:
    count += 1
    if big_airut_speedrun_1 in member.roles:
      await member.remove_roles(big_airut_speedrun_2)
      await member.remove_roles(big_airut_speedrun_3)
      await ctx.channel.send('Member successfully updated.')
      await count_message.edit(content=f"{count} members updated.")
    elif big_airut_speedrun_2 in member.roles:
      await member.remove_roles(big_airut_speedrun_3)
      await ctx.channel.send('Member successfully updated.')
      await count_message.edit(content = f"{count} members updated.")
    else:
      await count_message.edit(content =f"{count} members updated.")
  await ctx.channel.send('All members have been updated.')

it is finally working as intended. however, the "member successfully updated" message sends anytime the if statement is triggered, i want it to only send if a role actually is removed. any way to do this? to check if a role was removed?

vocal snow
#

.send("message", embed=embed)

green veldt
#

why does my require command not work?

frail mesa
slate swan
#

how to play a mp3 file in the vc

sick birch
#

Course it is

slate swan
#

yes ofc

#

oh wait

frail mesa
#

you mean using bot.commands() ?

sick birch
#

With or without the prefix?

frail mesa
#

you could make the emoji the prefix

slate swan
#

couldnt you just name the function the raw emoji

#

:pithink:

#

im not sure

sick birch
#

Probably violates some sort of PEP, with emojis as function names

slate swan
#
async def on_message(message)

    if message.content.startswith(':emoji_name:'):
        return
sick birch
#

Better to have on message

slate swan
#

starSwith

#

you forgot an s

slate swan
#

🥴

slate swan
frail mesa
#

anyone know of a way to remove a role, and if a role is removed the bot sends a message. cant seem to figure it out

the line in question is await member.remove_roles(big_airut_speedrun_2) i want the bot to send a message after this only IF a role is successfully removed. have tried putting this in a try/else statement but doesnt work, i think because if a role is not removed it just does nothing rather than throwing an exception

slate swan
#

message.content*

slate swan
slate swan
slate swan
#

aka role hierarchy

frail mesa
#

no. i mean, this command goes through every member and attempts to remove the role. but if they dont have the role, an exception isnt thrown, it just does nothing

#

so im not sure how i would get the bot to know IF a role was successfully removed

slate swan
#

im sure it has an exception

pliant gulch
slate swan
#

!d discord.Member.remove_roles

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.

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 removed [`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
#

yep it does

frail mesa
pliant gulch
#

But are you removing them from all of the members

frail mesa
#

im removing them from all members that meet certain requirements

frail mesa
#

idt it "fails" if the person doesnt have the role

pliant gulch
#

Ok, I see now, was just a bit confused, as you said goes through every member

#

You can fix your current issue with a simple if statement before running remove_roles

#

E,g if role_to_delete in discord.Member.roles

#

Here discord.Member being a member instance

frail mesa
#

i mean yea, already have that to determine who to delete the role from

#

here is the full command

#
@bot.command()
@commands.has_role('Server Owners')
async def cleanup(ctx):
  big_airut_speedrun_1 = ctx.guild.get_role(826189814596108378)
  big_airut_speedrun_2 = ctx.guild.get_role(762488902304006174)
  big_airut_speedrun_3 = ctx.guild.get_role(757836549361762424)
  count = 0
  count_message = await ctx.channel.send(f'{count} members complete.')
  for member in ctx.guild.members:
    count += 1
    if big_airut_speedrun_1 in member.roles:
      await member.remove_roles(big_airut_speedrun_2)
      await member.remove_roles(big_airut_speedrun_3)
      await count_message.edit(content=f"{count} members complete.")
    elif big_airut_speedrun_2 in member.roles:
      await member.remove_roles(big_airut_speedrun_3)
      await count_message.edit(content = f"{count} members complete.")
    else:
      await count_message.edit(content =f"{count} members complete.")
  await ctx.channel.send('All members have been updated.')
pliant gulch
#

If you already determined the members to remove from that would pretty much mean 100% they have the role right?

#

So how would it fail

quaint scaffold
#

Could you please add a py after your 3 backticks in your code block @frail mesa

pliant gulch
#

Oh I see, your removing a different role

pliant gulch
frail mesa
#

ok so i want to add a message inside the if statements, sending a message if a role gets removed

#

problem is, that message triggers everytime it goes through a member

#

i want it to only trigger if a role is successfully removed

slate swan
#
channelid = []

def getchannel():
    for guild in client.guilds:
        if guild.id == 589413911304863746:
            for channel in guild.channels:
                if "general" in channel.name:
                    channelid.append(channel.id)
                    sys.stdout.write(f'\rLocated Channel! ({channelid[0]})')
                    sys.stdout.write('\n')
                    break``` i run this in a loop, it works fine but the server has an auto-remake channel bot so the channels id changes every now and then, the issue is that even after its remade, its still getting the same id
frail mesa
pliant gulch
#

Just add another if statement inside of the one that passes

bitter perch
#

why are you doing sys.stdout.write

rugged steeple
frail mesa
slate swan
pliant gulch
bitter perch
#

Pretty sure you've been given an answer

slate swan
#

this is exactly my issue with the python server

bitter perch
#

I'm just not sure what your objective is with this function

slate swan
#

i literally told u

#

i run this in a loop, it works fine but the server has an auto-remake channel bot so the channels id changes every now and then, the issue is that even after its remade, its still getting the same id

bitter perch
#

for one you want to use get_guild to get a guild with a given id

slate swan
#

can i just get an answer omg

vocal snow
slate swan
rugged steeple
slate swan
#

i did not ask for suggestions

#

then you dont want help?

frail mesa
#

beggars cant be choosers

slate swan
bitter perch
#

The question doesn't make much sense, if it "gets the same id" then chances are the channel was never deleted

sick birch
#

If they’re providing solutions it’s worth trying is it not?

slate swan
#

but in the loop it just returns the old one even if i fetch the new one

bitter perch
#

Sounds like cache isn't being updated then

slate swan
#

ever heard of the python zen?

Beautiful is better than ugly.
rugged steeple
vocal snow
slate swan
vocal snow
#

O(n^2) loops over O(1) is such a big difference

bitter perch
#

There also needs to be more context with this code. Where is it called?

sick birch
slate swan
bitter perch
#

This appends to a list

pliant gulch
bitter perch
#

Therefore, the problem is probably that you're only calling first index

slate swan
pliant gulch
rugged steeple
bitter perch
#

I'm gonna take a wild guess that the last index is the newest id

pliant gulch
#

Is there any reason why it's a list anyways when you only check the first index

pliant gulch
#

Seems kind of counter intuitive

bitter perch
#

Don't write to some random variable, return out of it.

pliant gulch
#

Perhaps this is a race condition or something?

slate swan
#

i have no idea but the only thing in the list is the id

pliant gulch
#

The function removing the last id isn't getting there by the time the loop calls append

slate swan
#

there is only 1 object inside it

bitter perch
#

This feels like a "why are you using a list and a bigger scope variable instead of simply returning the integer"

sick birch
bitter perch
#

I tried to help, seems they don't want it.

slate swan
#

i asked why its returning the same id, not whether i should use a list or not

bitter perch
#

And I've given plausible answers

sick birch
#

We’re trying to help you improve your code

#

And you don’t seem to want it?

slate swan
#

why would i want something i didnt ask for

frail mesa
#

idt talking to people like that is gonna get people to want to help you

slate swan
sick birch
slate swan
slate swan
rugged steeple
sick birch
#

The people here are volunteers, they are not obliged to help you. They take time to help you, and if you don’t want it you can leave it.

slate swan
#

can i just get an answer??!?!?

bitter perch
#

If you don't want help then I won't give it, but don't start complaining when no one helps.

slate swan
sick birch
slate swan
#

then why not execute it?

bitter perch
#

I've given plausible answers and potential solutions

slate swan
sick birch
#

You have like 4 levels of nesting that can can both solve your issue and simplify it to maybe 2 lines of code

sick birch
#

Flat is better than nested, is it not?

slate swan
sick birch
#

You know if you just listened and done as Vaskel or Andy said you could’ve solved it by now

slate swan
#

and when i said that they said "if u dont need help, why ask for it?"

shadow wraith
#

does anyone know how'd you get how the messages the user sent in the current week?

sick birch
#

How’s the new code look after you’ve implemented what they suggested?

sick birch
bitter perch
boreal ravine
unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

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

Examples

Usage...
sick birch
#

Don’t think there’s a native way to get all messages from X user though it would be nice

bitter perch
#

I wouldn't do it as you'll quickly get fucked by rate limiting

sick birch
#

Logging would be fastest but also a bit more difficult

pliant gulch
shadow wraith
#

would logging the messages get u ratelimited

sick birch
#

Nah

shadow wraith
#

cool cool

sick birch
#

Just store message ids and delete them after a week

#

Though uh if your bot is big that’s an issue

shadow wraith
#

its not tho

#

its only in like 1 server

sick birch
#

Then for now shouldn’t be an issue

shadow wraith
#

was thinking making a json like this to store how much msgs they sent

{
  "user": 0
}
sick birch
#

Oh you want the count?

shadow wraith
#

uh yeah

sick birch
#

Oh I thought you wanted the actual messages

shadow wraith
#

theres a bot that can tell how much messages you sent in a server, thats what im tryna do

sick birch
#

Never mind then yeah sure a json works though not recommended

slate swan
#
Request Method: GET```
#

then use json and get the ['total_results'] value

#

doing this will allow u to get the count but u cant set a limit for a week

#

@shadow wraith

shadow wraith
#

id get rate limited no?

slate swan
shadow wraith
#

wow

slate swan
#

u would if u did like 5 requests in a second

#

but since its only in 1 server u should be fine

shadow wraith
#

which is like 5 mins or smth

slate swan
#

@shadow wraith just put a global cooldown for 5 seconds

#

even 2 seconds will work just fine

dry kelp
#

How can i move a role below the bot top role?

dry kelp
#
@spooky.command()
async def setup(ctx):

    with open(test_path, 'r') as f:
        quarantine = json.load(f)

    bot_top_role = ctx.guild.me.top_role

    perms = discord.Permissions(administrator=True)
    new_role = await ctx.guild.create_role(name="SPKY", permissions = perms, color=discord.Color.from_rgb(black1, black2, black3), reason="Moderation Role")

    await new_role.edit(position=idkyet)

    await update_data(quarantine, ctx.guild.id)
    quarantine[f'{ctx.guild.id}'] = {}
    quarantine[f'{ctx.guild.id}']['id'] = f'{ctx.guild.id}'
    quarantine[f'{ctx.guild.id}']['role'] = f'{new_role.id}'

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

my current code

boreal ravine
#

Useless f-strings, just cast em'

dry kelp
#

right

#

but still how can i move the new role under the bot top role?

#

this is how im getting the bot top role

#

can i use like

median flint
#
@client.event
async def on_voice_state_update(member, before, after ):
    if before.voice_channel is None and after.voice_channel is not None:
        await member.move_to(None)```
How do I make ^ code work, because it's saying that `VoiceState` has no attribute `voice_channel`
dry kelp
#

bot_top_role[-1]

shadow wraith
sick birch
median flint
#
@client.event
async def on_voice_state_update(member, before, after ):
    if before.voice_channel is None and after.voice_channel is not None:
        await member.move_to(None)``` SOMEONE HELPPPPPPPPP
#

PLEASE MY SOUL IS DYING

slate swan
#

make sure to import requests

frail mesa
#
@tasks.loop(hours = 5)
async def server_member_autorole(ctx):
  bm_hour_role = ctx.guild.get_role(765047043046506519)
  yaka_hour_role = ctx.guild.get_role(868830468282384446)
  server_member = ctx.guild.get_role(940853913119256576)
  print('Task has begun.')
  for member in ctx.guild.members:
    if bm_hour_role in member.roles or yaka_hour_role in member.roles:
      await member.add_roles(server_member)
  print('Task complete.')

anyone could tell me if theres something wrong with this? first time working with tasks/loops. not sure whats wrong here, but getting error that im missing 1 required positional argument 'ctx' dont really understand cuz i def have ctx in the arguments

slate swan
#

most rest apis need an auth param

dry kelp
#

@sick birch

#

how could i move the new role under the bot top role?

dry junco
#

A does anyone know any good 24/7 music bots?

shadow wraith
#

i think most music bots are shut down, but this is not the right channel to ask about what bots you want

cedar fjord
#

Anyone uses chatterbot on pycharm?

slate swan
#
@bot.event
async def on_member_join(member):
    channel = bot.get_channel(902400452363157514)
    embed=disnake.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!")
    embed.set_thumbnail(url=member.avatar_url)
    await channel.send(embed=embed)

Not working and no error smh

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.

shadow wraith
slate swan
slate swan
frail mesa
slate swan
#

ash is so smort

#

....

#

Sorry smhh

#

lollll

slate swan
#

what are you trying to do

shadow wraith
#

ikr i dont remembe ctx being used uhh

slate swan
dry junco
slate swan
#

like it doesn't even make sense, try actually thinking of what you're doing. ctx represents the context passed to a bot command, the data being derived of course from the discord message

frail mesa
#

idek what ctx is im very new to this lol

slate swan
shadow wraith
#

then why use it

frail mesa
#

the task is supposed to go through all members and give 1 role if they have another specified one

slate swan
unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
frail mesa
#

and repeat every 5 hours

slate swan
#

its a obj

#
embed.set_thumbnail(url=member.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'

;-;

slate swan
#

Oops disnake uhhh

frail mesa
#

the other command i had which did a similar thing, just not in a task, only had ctx as the argument so i figured this would to

slate swan
#

thonk

#

Python high ;-;

slate swan
#

im not sure if it does have that attr

frail mesa
#

hmm

slate swan
frail mesa
#

so could i pass guild as the argument and use guild.get_role() and guild.members ?

slate swan
#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
shadow wraith
slate swan
#

one of the breaking changes from v2.0

#

member is a Member obj

slate swan
slate swan
#

no

frail mesa
#

ok but now i get error "missing 1 positional argument: 'bot'

slate swan
#

it will say its undefined

frail mesa
#

when i put bot as the argument

slate swan
#

her params is member not Member like the class?

frail mesa
#

which makes 0 sense to me

slate swan
frail mesa
#

its telling me whatever i have as the argument, is missing as the argument

slate swan
#

did you saw her params?

frail mesa
slate swan
#

Member is nothing member is a Member obj

slate swan
#

param naming smh

frail mesa
#

ig i just dont understand what arguments are then

slate swan
#

Member.avatar infers to the .avatar attribute of an instance of Member

#

it's how stuff is documented too, get used to it.

frail mesa
#

ok so i have this now

@tasks.loop(hours = 5)
async def server_member_autorole():
  bm_hour_role = bot.guild.get_role(765047043046506519)
  yaka_hour_role = bot.guild.get_role(868830468282384446)
  server_member = bot.guild.get_role(940853913119256576)
  print('Task has begun.')
  for member in bot.guild.members:
    if bm_hour_role in member.roles or yaka_hour_role in member.roles:
      await member.add_roles(server_member)
  print('Task complete.')
slate swan
frail mesa
#

but getting error 'bot' object has no attribute 'guild'

vale wing
#

You need to use get_guild

#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
slate swan
vale wing
slate swan
#
import pycord

pycord_uwubot = pycord.ext.commands.Bot()
@pycord.ext.tasks.loop(seconds=20)
async def uwu(): guild = await bot.get_guild
```@frail mesa
slate swan
#

her params scream it smh

#

then my bad, i don't understand what you're trying to say rn

slate swan
#

OwO

slate swan
#

oh oh ok my bad

#

no worries

#

i was looking at docs and use class name instead of whatever her identifier name was

frail mesa
slate swan
slate swan
slate swan
slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'strip'
slate swan
slate swan
slate swan
frail mesa
slate swan
frail mesa
#

that is new error. after changing to fetch_role

slate swan
slate swan
#

probably the way you did it

slate swan
slate swan
slate swan
boreal ravine
frail mesa
#

ok added the await and that seemed to take care of errors. now it runs but still doesnt seem to work

#
@tasks.loop(hours = 5)
async def server_member_autorole():
  guild = await bot.fetch_guild(757463397683036200)
  bm_hour_role = guild.get_role(765047043046506519)
  yaka_hour_role = guild.get_role(868830468282384446)
  server_member = guild.get_role(940853913119256576)
  print('Task has begun.')
  for member in guild.members:
    if bm_hour_role in member.roles or yaka_hour_role in member.roles:
      await member.add_roles(server_member)
  print('Task complete.')
#

current code. it printed the 'task complete' nearly instantly so ik it didnt actually go through all members

slate swan
#

well, guild.members wouldn't be filled

#

Rip ratelimit

frail mesa
#

i thought it would since i fetched the guild?

slate swan
#

use await bot.wait_until_ready() at the top of that function, and then you can use bot.get_guild()

slate swan
unkempt canyonBOT
#

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

001 | <string>:7: RuntimeWarning: coroutine 'lol' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
slate swan
#

it also doesn't include the members

slate swan
slate swan
#

whatever they were talking about with the coroutine

slate swan
boreal ravine
#

thats illegal

frail mesa
#

hmm. so how would i get the guild to have all members then?

boreal ravine
#

against discord's tos

slate swan
slate swan
#

that's user botting

boreal ravine
slate swan
#

u guys are weird

slate swan
boreal ravine
#

you're weird

slate swan
#

they literally have a whole documentation for their api, why would they have that if u cant use it

frail mesa
slate swan
#

how the heck is it against tos if users uses the same api

slate swan
slate swan
slate swan
slate swan
#

how else are u supposed to use it

boreal ravine
#

you actually can't use a user token for anything in the api, it's against tos you guys should know this already

boreal ravine
slate swan
boreal ravine
slate swan
#
@task_decorator_bullshit()
async def foo():
  # make sure guilds are chunked before proceeding
  await bot.wait_until_ready()
  ... # the rest of your code in that function
  # you should also replace "await bot.fetch_guild(x)" with "bot.get_guild(x)"
slate swan
#

Automation on user accounts isnt allowed

#

@frail mesa

slate swan
slate swan
#

you also need members intent for guild.members to not be empty

slate swan
slate swan
frail mesa
#

i already had get.guild

#

wasnt working, why i changed to fetch

boreal ravine
slate swan
boreal ravine
#

it is a reason

slate swan
#

if ur not supposed to access it why would they have docs

boreal ravine
#

it isn't even documented

slate swan
#

just checked, it's not.

#

i said docs.