This is the code:
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
#discord.ui.Button(label='Create a ticket', style = discord.ButtonStyle.blurple, custom_id = 'ticket_button')
async def ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
ticket = discord.utils.get(interaction.guild.text_channels, name = f'ticket-for-{interaction.user.name}-{interaction.user.discriminator}')
if ticket is not None: await interaction.response.send_message(f'You already have a ticket open at {ticket.mention}!', ephemeral = True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
channel = await interaction.guild.create_text_channel(name=f'ticket-for-{interaction.user.name}-{interaction.user.discriminator}', overwrites=overwrites, reason=f'Ticket for {interaction.user}.')
await channel.send(f'{interaction.user.mention} created a ticket!')
await interaction.response.send_message(f'I have opened a ticket for you at {channel.mention}.', ephemeral=True)
tree = app_commands.CommandTree(client=client)
#tree.command(guild = discord.Object(id=TICKET_CHANNEL), name='ticket', description='Launches the ticket system.')
async def ticket(interaction: discord.Interaction):
embed = discord.Embed(title='If you have any problems click the big blue button below!', color=discord.Colour.blue())
await interaction.channel.send(embed=embed, view=ticket_launcher())
await interaction.response.send_message('Ticketing system has been launched successfully.', ephemeral=True)
it gives me this error message in the output:
Traceback (most recent call last):
File "c:\Users\schul\Desktop\MORE PYTHON\bot.py", line 214, in <module>
class ticket_launcher(discord.ui.View):
File "c:\Users\schul\Desktop\MORE PYTHON\bot.py", line 219, in ticket_launcher
async def ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
TypeError: 'Button' object is not callable
So can anyone mind helping me out with this, as this kinda annoying, would be thankfull if you would've helped me out :)
In your button decorator, use button in lowercase:
#discord.ui.button(label='Create a ticket', style = discord.ButtonStyle.blurple, custom_id = 'ticket_button')
Docs: https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=button#discord.ui.button
Related
I am working on building an asyncio.Future integration with my Tornado app so I can request a callback. Essentially, I instantiated a class within a class, this creates a future and adds a callback to the function.
However, when I call this I get a bunch of error messages:
Traceback (most recent call last):
File "/Users/robot/tornado/venv/lib/python3.8/site-packages/tornado/web.py", line 1713, in _execute
result = await result
File "pending/request_seven.py", line 31, in get
await self.scheduleFuture._future(client.fetch('https://books.toscrape.com'), self.on_response)
File "pending/request_seven.py", line 25, in _future
fut = self.create_future()
AttributeError: '_asyncio.Future' object has no attribute 'create_future'
Here is what I have tried with my script:
define('port', default = 9057, help="run port 9060", type=int)
class requestFour(tornado.web.RequestHandler):
class scheduleFuture(asyncio.SelectorEventLoop):
#staticmethod
def unwrapper(fut: asyncio.Future, function):
return function()
def _future(self, fun1 ):
fut = self.create_future()
fut.add_done_callback(func(self.unwrapper, function=fun1))
return fut
async def get(self):
client = tornado.httpclient.AsyncHTTPClient()
await self.scheduleFuture._future(client.fetch('https://books.toscrape.com'), self.on_response)
def on_response(self, response):
body = response.body
self.write(body)
self.finish()
def my_app():
app = tornado.web.Application(handlers = [(r'/', requestFour)])
http_server = tornado.httpserver.HTTPServer(app)
return http_server
async def main():
app = my_app()
app.listen(options.port)
shutdown_event = asyncio.Event()
await shutdown_event.wait()
if __name__ == '__main__':
asyncio.run(main())
#bot.command(aliasses=['QUEUE', 'queue', 'q', 'Q'])
async def queue(ctx):
member = ctx.message.author
voice_state = ctx.member.voice
QAPI = ctx.message.author.id
if voice_state is None:
await ctx.send(f'You need to be in "<#1022558265348980796>" Channel to use that ')
else:
await ctx.send(f'You been putted in Queue. "<#{QAPI}')
AttributeError: 'Context' object has no attribute 'member'
i can't get it. i setted the member, i specify what is voice_state.. any ideeas?
How to fix the error, but at the same time the class and self should remain?
Here Are the TraceBack:
Traceback (most recent call last):
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
And here are the code:
#!/usr/bin/python3
from discord.ext import commands
import discord
import inspect
class StarBot(commands.Bot):
def __init__(self, command_prefix, **options):
super().__init__(command_prefix, **options)
members = inspect.getmembers(self)
for name, member in members:
if isinstance(member, commands.Command):
if member.parent is None:
self.add_command(member)
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
#commands.command(name='reg', help='Для регистрации', pass_context=True)
async def reg(self, ctx):
if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message':
await self.embed(ctx.channel, "Начало регистрации")
async def embed_channel(self, channel, title, string='', color=0xff9900):
embed = discord.Embed(color=color, title=title, description=string)
msg = await channel.send(embed=embed)
return msg
intents = discord.Intents.all()
bot = StarBot(command_prefix='/', intents=intents)
bot.run(TOKEN)
The issue with the code here:
#commands.command(name='reg', help='Для регистрации', pass_context=True)
async def reg(self, ctx):
if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message':
await self.embed(ctx.channel, "Начало регистрации")
Here, you have (self,ctx):
async def reg(self, ctx):
In a cog it needs to be (client,ctx):
async def reg(client, ctx):
It should look like:
#commands.command(name='reg', help='Для регистрации', pass_context=True)
async def reg(client, ctx):
if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message':
await self.embed(ctx.channel, "Начало регистрации")
I recenlty added a code from google api serve=ive and it's causing my entire script to not reponding except for the event :
#bot.event
async def on_message(msg):
analyze_request = {'comment': { 'text': msg.content }, 'requestedAttributes': {'TOXICITY': {}}}
response = service.comments().analyze(body=analyze_request).execute()
spanScore = response['attributeScores']['TOXICITY']['spanScores']
value = spanScore[0]['score']['value']
print(value * 100)
toxicity = value * 100
if toxicity > 95:
await msg.author.kick(reason = "Toxic messages")
await msg.author.send('You were kicked because you sent toxic message(s)')
await msg.send(f"{msg.author}, has been kicked for being toxic !")
elif toxicity > 70 and toxicity < 94:
await msg.channel.send(f"{msg.author.mention}, please watch your language")
Thanks for futur anwsers
You need to process the commands, add the following at the end of your on_message event:
await bot.process_commands(message)
More information regarding this topic on the documentation
I've been trying to figure this out forever now, but it seems that my discord.py command prefix for my bot does not work. Currently, here is my code:
players = {}
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
await client.change_presence(activity=discord.Game(name="with your words!"))
called_once_an_hour.start()
#client.command()
async def test():
await client.send('test')
#client.command(pass_context = True)
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
#client.command(pass_context = True)
async def leave(ctx):
server = ctx.message.server
voice_client = client.voice_client_in(server)
await voice_client.disconnect()
#client.command(pass_context = True)
async def play(ctx):
server = ctx.message.server
voice_client = client.voice_client_in(server)
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=YMw-9mXfccY')
players[server.id] = player
player.start()
print(f"Playing Are you winning son in server voice client: {voice_client}")
First client command was mainly for debugging purposes, but its just never called out.
I also think I already have all the necessary imports
Your test command needs to look like:
async def test(ctx):
await ctx.send('test')
I can run this successfully with !test
The context is passed by default, pass_context = True is no longer necessary.
See the commands docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html