This is working perfectly without a COG, But in the COG It's not working and generating the following errors:
NameError: name 'bot' is not defined
import discord
from discord.ext import commands
class channelinfo(commands.Cog):
##commands.Cog.listener() [EVENT]
##commands.command() [COMMAND]
def init(self, bot):
self.bot = bot
#commands.command()
async def channelinfo(self,ctx,*,val:str = None):
val = val.replace('<','')
val = val.replace('>','')
val = val.replace('#','')
print(val)
channel = await bot.get_channel(int(val))
Even the discord.User is not working in the COG.
Error: Command raised an exception: AttributeError: 'User' object has no attribute 'roles'
#commands.command()
async def userinfo(self,ctx,user:discord.User = None):
msg = ''
for a in user.roles:
msg+= a.name
Have you tried
channel = await self.bot.get_channel(int(val))
Related
I have a problem with my code from my discord bot. When I run the program I get an error message, but I have all imports up to date. Can someone help me please, because I really have no idea how to fix this . If you have any more questions just write in.
Here is the error:
AttributeError: module 'discord' has no attribute 'ui'
And Here is my Code:
import discord
from discord.ext import commands
from discord_ui import ButtonInteraction, Button, ButtonStyle, UI
intent = discord.Intents.default()
intent.members = True
bot = commands.Bot(command_prefix="!", intent=intent)
role_id = 938465872098512956
guild_id = 938215477157703771
class RoleButton(discord.ui.Button):
def __init__(self):
super().__init__(
label="Verifiziere dich hier!",
style=discord.enums.ButtonStyle.blurple,
custom_id="interaction:RoleButton",
)
async def callback(self, interaction: discord.Interaction):
user = interaction.user
role = interaction.guild.get_role(role_id)
if role is None:
return
if role not in user.roles:
await user.add_roles(role)
await interaction.response.send_message(f"🎉 Du bist nun verifiziert!", ephemeral=True)
else:
await interaction.response.send_message(f"❌ Du bist bereits verifiziert!", ephemeral=True)
BILD_URL = ""
BESCHREIBUNG = "Test"
#bot.command()
async def post(ctx: commands.Context): # Command
view = discord.ui.View(timeout=None)
view.add_item(RoleButton())
await ctx.send(f"{BILD_URL}")
await ctx.send(f"{BESCHREIBUNG}", view=view)
#bot.event
async def on_ready():
print("ONLINE!")
view = discord.ui.View(timeout=None)
view.add_item(RoleButton())
bot.add_view(view)
bot.run("")
My code is returning this error NoneType object has no attribute 'send'
here is my code
import discord
import os
from discord.ext import commands
client = discord.Client()
class Logging(commands.Cog):
"""Sets up logging for you guild"""
def __init__(self, client):
self.bot = client
async def __error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
#commands.Cog.listener()
async def on_message_delete(self, message,):
deleted = embed = discord.Embed(
description=f"Message deleted in {message.channel.mention}", color=0x4040EC
).set_author(name=message.author, url= discord.Embed.Empty, icon_url=message.author.avatar_url)
channel = client.get_channel(888600482317213786)
deleted.add_field(name="Message", value=message.content)
deleted.timestamp = message.created_at
await channel.send(embed=deleted)
def setup(client):
client.add_cog(Logging(client))
I am doing this in my cogs and not in the main.py
channel = client.get_channel(888600482317213786) should be channel = self.bot.get_channel(888600482317213786). Then check if channel is None.
I assume there is no indentation error in your actual code.
import discord
from discord.ext import commands
class AntiCog(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == 1234567891234567:
mention = f'<#!1234567891234567>'
if message.content == mention:
await message.channel.send("grow up")
user = message.author
print(str(user))
print(str(message.content))
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await user.add_roles(muted_role)
else:
return
await self.client.process_commands(message)
def setup(client):
client.add_cog(AntiCog(client))
This's a working code for muting a person if they ping another person, however, I would like to make it a timed mute for 5 min. All of the resources I found were on_command timed mute, however, this's an auto one, how can I do so. thank you!
All you would have to do is add asyncio.sleep, and then remove the role, so:
import discord
from discord.ext import commands
import asyncio
class AntiCog(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == 1234567891234567:
mention = f'<#!1234567891234567>'
if message.content == mention:
await message.channel.send("grow up")
user = message.author
print(str(user))
print(str(message.content))
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await user.add_roles(muted_role)
await asyncio.sleep(300) # you can change the time here
await user.remove_roles(muted_role)
else:
return
await self.client.process_commands(message)
def setup(client):
client.add_cog(AntiCog(client))
Be sure to import asyncio!
My Current Project
I am currently trying to make a cog for a Discord bot in Python 3 that, when running, plays a specific audio file when someone joins a specific Discord voice channel.
My Problem
I already have the code for my project(credit: Tabulate), but I don't know how to
Convert it to a cog, and
Make it work for a specific voice channel, and not every one in the Discord
server.
Here's my code:
import discord
from discord.ext import commands
from time import sleep
rpgmusicpath = r"C:\Users\lones\OneDrive\Desktop\Bot\music\rpgmusic.mp3"
class VoiceChannelIntro(commands.Cog):
def __init__(self, client):
self.bot = client
#commands.Cog.listener()
async def on_ready(self):
print('Channel Intro cog successfully loaded.')
#commands.Cog.event
async def on_voice_state_update(member: discord.Member, before, after):
#replace this with the path to your audio file
path = r"path\to\music.mp3"
vc_before = before.channel
vc_after = after.channel
if vc_before == vc_after:
return
elif vc_before is None:
channel = member.voice.channel
vc = await channel.connect()
vc.play(discord.FFmpegPCMAudio(path))
with audioread.audio_open(path) as f:
#Start Playing
sleep(f.duration)
await vc.disconnect()
elif vc_after is None:
return
else:
channel = member.voice.channel
vc = await channel.connect()
vc.play(discord.FFmpegPCMAudio(path))
with audioread.audio_open(path) as f:
#Start Playing
sleep(f.duration)
await vc.disconnect()
def setup(bot):
bot.add_cog(VoiceChannelIntro(bot))
Here are some of your mistakes:
Use asyncio.sleep() instead of time.sleep()
You forgot to pass self as the first argument
Below is the revised code:
import discord
from discord.ext import commands
from asyncio import sleep
rpgmusicpath = r"C:\Users\lones\OneDrive\Desktop\Bot\music\rpgmusic.mp3"
class Music(commands.Cog):
def __init__(self, client):
self.bot = client
#commands.Cog.listener()
async def on_ready(self):
print('Music cog successfully loaded.')
#commands.Cog.event
async def on_voice_state_update(self, member, before, after):
#replace this with the path to your audio file
path = r"C:\Users\lones\OneDrive\Desktop\Bot\test-chamber-4-intro.mp3"
vc_before = before.channel
vc_after = after.channel
if not vc_before and vc_after.id == YOUR VOICE CHANNEL ID:
vc = await vc_after.connect()
vc.play(discord.FFmpegPCMAudio(path))
with audioread.audio_open(path) as f:
#Start Playing
sleep(f.duration)
await vc.disconnect()
def setup(bot):
bot.add_cog(Music(bot))
I am trying to make a selfbot for discord in discord.py rewrite and it gives me this error:
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "me" is not found
Here is my code:
from discord.ext import commands
selfbot = commands.Bot(command_prefix = "<.", self_bot = True)
selfbot.event
async def on_ready():
print(f'IDK Running on: {selfbot.user}')
selfbot.command()
async def test(ctx):
await ctx.send('Off.')
selfbot.command()
async def me(ctx):
ctx.send(f'You are {selfbot.user}')
token = 'token here'
selfbot.run(token, bot = False)```
you're missing #. It should've been
from discord.ext import commands
selfbot = commands.Bot(command_prefix = "<.", self_bot = True)
#selfbot.event
async def on_ready():
print(f'IDK Running on: {selfbot.user}')
#selfbot.command()
async def test(ctx):
await ctx.send('Off.')
#selfbot.command()
async def me(ctx):
ctx.send(f'You are {selfbot.user}')
token = 'token here'
selfbot.run(token, bot = False)
Note: You're missing the command decorator main thing, #, without it, your command will not register as a command or a event