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("")
Related
I am making a Discord Bot that plays music when I give it the name of a song.
Whenever I give it the ".play" command, the Discord app shows that the bot is in fact playing audio, I just don't hear any.
I tried multiple times with different music, however I recieved the same problem.
Here is my code:
import discord
from discord.ext import commands
import wavelink
client = commands.Bot(command_prefix = ".", intents = discord.Intents.all())
class CustomPlayer (wavelink.Player):
def __init__(self):
super().__init__()
self.queue = wavelink.Queue()
#client.event
async def on_ready():
client.loop.create_task(connect_nodes()) #HTTPS and Websocket operations
async def connect_nodes(): #Helper function
await client.wait_until_ready()
await wavelink.NodePool.create_node(
bot = client ,
host = "127.0.0.1" ,
port = 2333 ,
password = "youshallnotpass"
)
#client.event
async def on_wavelink_node_ready(node = wavelink.Node):
print(f"Node: <{node.identifier}> is ready!")
#client.command()
async def connect(ctx):
vc = ctx.voice_client
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send("Please join a channel to connect.")
if not vc:
await ctx.author.voice.channel.connect(cls = CustomPlayer())
else:
await ctx.send("The bot is already connected to a voice channel.")
#client.command()
async def disconnect(ctx):
vc = ctx.voice_client
if vc:
await vc.disconnect()
else:
await ctx.send("Bot is not connected to a voice channel.")
#client.command()
async def play(ctx, *, search: wavelink.YouTubeTrack):
vc = ctx.voice_client #represents a discord voice connection
if not vc:
custom_player = CustomPlayer()
vc: CustomPlayer = await ctx.author.voice.channel.connect(cls = custom_player)
if vc.is_playing():
vc.queue.put(item = search)
await ctx.send(embed = discord.Embed(
title = search.title,
url = search.uri,
description = f"Queued {search.title} in {vc.channel}"
))
else:
await vc.play(search)
await ctx.send(embed = discord.Embed(
title = search.title,
url = search.uri,
description = f"Playing {vc.source.title} in {vc.channel}"))
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!
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))
I have a problem with the discord.py Python library. I'm getting an error, every time someone reacts to messages.
Python do not show me, where the error comes from, but I think it's an error in the discord.py.
Last week the code worked but now its not working anymore. I'm becoming a headache about it. Can someone help my please?
Here is my code:
import discord
from emojis import emojis
import msg
from discord.utils import get
from discord.ext import commands
import json
from uuid import uuid4
shop_channels = []
orders = {}
cmd_prefix = "dsb!"
def check_perms(user):
for role in user.roles:
if role.name == "𝗢𝘄𝗻𝗲𝗿":
return True
return False
def check_command(message, command):
if message.startswith(cmd_prefix + command):
return True
else:
return False
def save_settings():
settings = {}
settings["shop_channels"] = shop_channels
settings["orders"] = orders
with open("data.json", "w") as file:
json.dump(settings, file)
def load_settings():
global shop_channels
global orders
with open("data.json") as file:
settings = json.load(file)
orders = settings["orders"]
shop_channels = settings["shop_channels"]
print(shop_channels)
class MyClient(discord.Client):
async def on_ready(self):
self.msg = msg.Msg(True, "DiShoBo")
print('-------')
print('Logged in as')
print('Username:', self.user.name)
print('ID:', self.user.id)
print('------', end="\n\n")
load_settings()
print("Settings loaded!\n\n")
async def on_reaction_add(self, reaction, user):
print("hello")
if shop_channels is None or reaction.message.channel.id not in shop_channels:
return
try:
if reaction.emoji == emojis["shopping_cart"]:
order_id = uuid4()
item = reaction.message.content.partition('\n')[0]
amount = reaction.message.content.partition('\n')[2]
self.msg.debug("Got new order from user {0} for Item: {1}! OrderID: {2}".format(
user, item, order_id))
if user.dm_channel == None:
await user.create_dm()
message = await user.dm_channel.send("You ({2}) added the Item: '{0}' for {1} to your shopping cart!\nClick on :white_check_mark: to finish your order then go back to Angels 2B2T shop, or if you want to keep shopping, just go back to the shop and add more items.\nIf you want to clear your shopping cart, click the {3} below.\n\nYour OrderID is: {4}".format(item, amount, user.mention, emojis["cross_mark"], order_id))
# await message.add_reaction(emojis["check_mark_box"])
# await message.add_reaction(emojis["cross_mark"])
if not message.author in orders:
orders.update(
{message.author: {"user": message.author, "ID": order_id, "items": []}})
print(orders[message.author]["items"])
orders[message.author]["items"].append({item, amount})
print(orders[message.author]["items"])
if not reaction.me and reaction.count > 1:
await reaction.remove(user)
else:
await reaction.remove(user)
except:
pass
# * CONNECT
client = MyClient()
client.run('TOKEN')
This was a bug on the hand of the discord.py library but was fixed in the update 1.3.2.