Fix code style issues with Black

This commit is contained in:
Lint Action
2021-09-05 21:34:20 +00:00
parent a23dae8604
commit 7513c2138f
108 changed files with 5369 additions and 4858 deletions

View File

@ -2,6 +2,7 @@ from discord.ext import tasks
import discord
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@ -13,18 +14,19 @@ class MyClient(discord.Client):
self.my_background_task.start()
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
@tasks.loop(seconds=60) # task runs every 60 seconds
@tasks.loop(seconds=60) # task runs every 60 seconds
async def my_background_task(self):
channel = self.get_channel(1234567) # channel ID goes here
channel = self.get_channel(1234567) # channel ID goes here
self.counter += 1
await channel.send(self.counter)
@my_background_task.before_loop
async def before_my_task(self):
await self.wait_until_ready() # wait until the bot logs in
await self.wait_until_ready() # wait until the bot logs in
client = MyClient(intents=discord.Intents(guilds=True))
client.run('token')
client.run("token")

View File

@ -1,6 +1,7 @@
import discord
import asyncio
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@ -9,18 +10,18 @@ class MyClient(discord.Client):
self.bg_task = self.loop.create_task(self.my_background_task())
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
async def my_background_task(self):
await self.wait_until_ready()
counter = 0
channel = self.get_channel(1234567) # channel ID goes here
channel = self.get_channel(1234567) # channel ID goes here
while not self.is_closed():
counter += 1
await channel.send(counter)
await asyncio.sleep(60) # task runs every 60 seconds
await asyncio.sleep(60) # task runs every 60 seconds
client = MyClient(intents=discord.Intents(guilds=True))
client.run('token')
client.run("token")

View File

@ -4,51 +4,58 @@ import discord
from discord.ext import commands
import random
description = '''An example bot to showcase the discord.ext.commands extension
description = """An example bot to showcase the discord.ext.commands extension
module.
There are a number of utility commands being showcased here.'''
There are a number of utility commands being showcased here."""
intents = discord.Intents(guilds=True, messages=True, members=True)
bot = commands.Bot(command_prefix='t-', description=description, intents=intents)
bot = commands.Bot(command_prefix="t-", description=description, intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
print("------")
@bot.command()
async def add(ctx, left: int, right: int):
"""Adds two numbers together."""
await ctx.send(left + right)
@bot.command()
async def roll(ctx, dice: str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
rolls, limit = map(int, dice.split("d"))
except Exception:
await ctx.send('Format has to be in NdN!')
await ctx.send("Format has to be in NdN!")
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
result = ", ".join(str(random.randint(1, limit)) for r in range(rolls))
await ctx.send(result)
@bot.command(description='For when you wanna settle the score some other way')
@bot.command(description="For when you wanna settle the score some other way")
async def choose(ctx, *choices: str):
"""Chooses between multiple choices."""
await ctx.send(random.choice(choices))
@bot.command()
async def repeat(ctx, times: int, content='repeating...'):
async def repeat(ctx, times: int, content="repeating..."):
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content)
@bot.command()
async def joined(ctx, member: discord.Member):
"""Says when a member joined."""
await ctx.send(f'{member.name} joined in {member.joined_at}')
await ctx.send(f"{member.name} joined in {member.joined_at}")
@bot.group()
async def cool(ctx):
@ -57,11 +64,13 @@ async def cool(ctx):
In reality this just checks if a subcommand is being invoked.
"""
if ctx.invoked_subcommand is None:
await ctx.send(f'No, {ctx.subcommand_passed} is not cool')
await ctx.send(f"No, {ctx.subcommand_passed} is not cool")
@cool.command(name='bot')
@cool.command(name="bot")
async def _bot(ctx):
"""Is the bot cool?"""
await ctx.send('Yes, the bot is cool.')
await ctx.send("Yes, the bot is cool.")
bot.run('token')
bot.run("token")

View File

@ -6,26 +6,24 @@ import youtube_dl
from discord.ext import commands
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
youtube_dl.utils.bug_reports_message = lambda: ""
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
"format": "bestaudio/best",
"outtmpl": "%(extractor)s-%(id)s-%(title)s.%(ext)s",
"restrictfilenames": True,
"noplaylist": True,
"nocheckcertificate": True,
"ignoreerrors": False,
"logtostderr": False,
"quiet": True,
"no_warnings": True,
"default_search": "auto",
"source_address": "0.0.0.0", # bind to ipv4 since ipv6 addresses cause issues sometimes
}
ffmpeg_options = {
'options': '-vn'
}
ffmpeg_options = {"options": "-vn"}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
@ -36,19 +34,19 @@ class YTDLSource(discord.PCMVolumeTransformer):
self.data = data
self.title = data.get('title')
self.url = data.get('url')
self.title = data.get("title")
self.url = data.get("url")
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
if "entries" in data:
# take first item from a playlist
data = data['entries'][0]
data = data["entries"][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
filename = data["url"] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
@ -70,9 +68,9 @@ class Music(commands.Cog):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)
ctx.voice_client.play(source, after=lambda e: print(f"Player error: {e}") if e else None)
await ctx.send(f'Now playing: {query}')
await ctx.send(f"Now playing: {query}")
@commands.command()
async def yt(self, ctx, *, url):
@ -80,9 +78,9 @@ class Music(commands.Cog):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
ctx.voice_client.play(player, after=lambda e: print(f"Player error: {e}") if e else None)
await ctx.send(f'Now playing: {player.title}')
await ctx.send(f"Now playing: {player.title}")
@commands.command()
async def stream(self, ctx, *, url):
@ -90,9 +88,9 @@ class Music(commands.Cog):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
ctx.voice_client.play(player, after=lambda e: print(f"Player error: {e}") if e else None)
await ctx.send(f'Now playing: {player.title}')
await ctx.send(f"Now playing: {player.title}")
@commands.command()
async def volume(self, ctx, volume: int):
@ -123,16 +121,19 @@ class Music(commands.Cog):
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"),
description='Relatively simple music bot example',
intents=discord.Intents(guilds=True, guild_messages=True, voice_states=True)
description="Relatively simple music bot example",
intents=discord.Intents(guilds=True, guild_messages=True, voice_states=True),
)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
print("------")
bot.add_cog(Music(bot))
bot.run('token')
bot.run("token")

View File

@ -7,7 +7,7 @@ from discord.ext import commands
intents = discord.Intents(guilds=True, messages=True, members=True)
bot = commands.Bot('!', intents=intents)
bot = commands.Bot("!", intents=intents)
@bot.command()
@ -28,14 +28,16 @@ async def userinfo(ctx: commands.Context, user: discord.User):
user_id = user.id
username = user.name
avatar = user.avatar.url
await ctx.send(f'User found: {user_id} -- {username}\n{avatar}')
await ctx.send(f"User found: {user_id} -- {username}\n{avatar}")
@userinfo.error
async def userinfo_error(ctx: commands.Context, error: commands.CommandError):
# if the conversion above fails for any reason, it will raise `commands.BadArgument`
# so we handle this in this error handler:
if isinstance(error, commands.BadArgument):
return await ctx.send('Couldn\'t find that user.')
return await ctx.send("Couldn't find that user.")
# Custom Converter here
class ChannelOrMemberConverter(commands.Converter):
@ -72,15 +74,15 @@ class ChannelOrMemberConverter(commands.Converter):
raise commands.BadArgument(f'No Member or TextChannel could be converted from "{argument}"')
@bot.command()
async def notify(ctx: commands.Context, target: ChannelOrMemberConverter):
# This command signature utilises the custom converter written above
# What will happen during command invocation is that the `target` above will be passed to
# the `argument` parameter of the `ChannelOrMemberConverter.convert` method and
# the `argument` parameter of the `ChannelOrMemberConverter.convert` method and
# the conversion will go through the process defined there.
await target.send(f'Hello, {target.name}!')
await target.send(f"Hello, {target.name}!")
@bot.command()
async def ignore(ctx: commands.Context, target: typing.Union[discord.Member, discord.TextChannel]):
@ -94,9 +96,10 @@ async def ignore(ctx: commands.Context, target: typing.Union[discord.Member, dis
# To check the resulting type, `isinstance` is used
if isinstance(target, discord.Member):
await ctx.send(f'Member found: {target.mention}, adding them to the ignore list.')
elif isinstance(target, discord.TextChannel): # this could be an `else` but for completeness' sake.
await ctx.send(f'Channel found: {target.mention}, adding it to the ignore list.')
await ctx.send(f"Member found: {target.mention}, adding them to the ignore list.")
elif isinstance(target, discord.TextChannel): # this could be an `else` but for completeness' sake.
await ctx.send(f"Channel found: {target.mention}, adding it to the ignore list.")
# Built-in type converters.
@bot.command()
@ -109,4 +112,5 @@ async def multiply(ctx: commands.Context, number: int, maybe: bool):
return await ctx.send(number * 2)
await ctx.send(number * 5)
bot.run('token')
bot.run("token")

View File

@ -10,7 +10,7 @@ class MyContext(commands.Context):
# depending on whether value is True or False
# if its True, it'll add a green check mark
# otherwise, it'll add a red cross mark
emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
emoji = "\N{WHITE HEAVY CHECK MARK}" if value else "\N{CROSS MARK}"
try:
# this will react to the command author's message
await self.message.add_reaction(emoji)
@ -27,13 +27,14 @@ class MyBot(commands.Bot):
# subclass to the super() method, which tells the bot to
# use the new MyContext class
return await super().get_context(message, cls=cls)
bot = MyBot(command_prefix='!', intents=discord.Intents(guilds=True, messages=True))
bot = MyBot(command_prefix="!", intents=discord.Intents(guilds=True, messages=True))
@bot.command()
async def guess(ctx, number: int):
""" Guess a random number from 1 to 6. """
"""Guess a random number from 1 to 6."""
# explained in a previous example, this gives you
# a random number from 1-6
value = random.randint(1, 6)
@ -42,8 +43,9 @@ async def guess(ctx, number: int):
# or a red cross mark if it wasn't
await ctx.tick(number == value)
# IMPORTANT: You shouldn't hard code your token
# these are very important, and leaking them can
# these are very important, and leaking them can
# let people do very malicious things with your
# bot. Try to use a file or something to keep
# them private, and don't commit it to GitHub

View File

@ -1,21 +1,23 @@
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
async def on_message(self, message):
if message.content.startswith('!deleteme'):
msg = await message.channel.send('I will delete myself now...')
if message.content.startswith("!deleteme"):
msg = await message.channel.send("I will delete myself now...")
await msg.delete()
# this also works
await message.channel.send('Goodbye in 3 seconds...', delete_after=3.0)
await message.channel.send("Goodbye in 3 seconds...", delete_after=3.0)
async def on_message_delete(self, message):
msg = f'{message.author} has deleted the message: {message.content}'
msg = f"{message.author} has deleted the message: {message.content}"
await message.channel.send(msg)
client = MyClient(intents=discord.Intents(guilds=True, messages=True))
client.run('token')
client.run("token")

View File

@ -1,20 +1,22 @@
import discord
import asyncio
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
async def on_message(self, message):
if message.content.startswith('!editme'):
msg = await message.channel.send('10')
if message.content.startswith("!editme"):
msg = await message.channel.send("10")
await asyncio.sleep(3.0)
await msg.edit(content='40')
await msg.edit(content="40")
async def on_message_edit(self, before, after):
msg = f'**{before.author}** edited their message:\n{before.content} -> {after.content}'
msg = f"**{before.author}** edited their message:\n{before.content} -> {after.content}"
await before.channel.send(msg)
client = MyClient(intents=discord.Intents(guilds=True, messages=True))
client.run('token')
client.run("token")

View File

@ -2,18 +2,19 @@ import discord
import random
import asyncio
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('$guess'):
await message.channel.send('Guess a number between 1 and 10.')
if message.content.startswith("$guess"):
await message.channel.send("Guess a number between 1 and 10.")
def is_correct(m):
return m.author == message.author and m.content.isdigit()
@ -21,14 +22,15 @@ class MyClient(discord.Client):
answer = random.randint(1, 10)
try:
guess = await self.wait_for('message', check=is_correct, timeout=5.0)
guess = await self.wait_for("message", check=is_correct, timeout=5.0)
except asyncio.TimeoutError:
return await message.channel.send(f'Sorry, you took too long it was {answer}.')
return await message.channel.send(f"Sorry, you took too long it was {answer}.")
if int(guess.content) == answer:
await message.channel.send('You are right!')
await message.channel.send("You are right!")
else:
await message.channel.send(f'Oops. It is actually {answer}.')
await message.channel.send(f"Oops. It is actually {answer}.")
client = MyClient(intents=discord.Intents(guilds=True, messages=True))
client.run('token')
client.run("token")

View File

@ -2,17 +2,18 @@
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = f'Welcome {member.mention} to {guild.name}!'
to_send = f"Welcome {member.mention} to {guild.name}!"
await guild.system_channel.send(to_send)
client = MyClient(intents=discord.Intents(guilds=True, members=True))
client.run('token')
client.run("token")

View File

@ -2,15 +2,16 @@
import discord
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.role_message_id = 0 # ID of the message that can be reacted to to add/remove a role.
self.role_message_id = 0 # ID of the message that can be reacted to to add/remove a role.
self.emoji_to_role = {
discord.PartialEmoji(name='🔴'): 0, # ID of the role associated with unicode emoji '🔴'.
discord.PartialEmoji(name='🟡'): 0, # ID of the role associated with unicode emoji '🟡'.
discord.PartialEmoji(name='green', id=0): 0, # ID of the role associated with a partial emoji's ID.
discord.PartialEmoji(name="🔴"): 0, # ID of the role associated with unicode emoji '🔴'.
discord.PartialEmoji(name="🟡"): 0, # ID of the role associated with unicode emoji '🟡'.
discord.PartialEmoji(name="green", id=0): 0, # ID of the role associated with a partial emoji's ID.
}
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
@ -78,6 +79,7 @@ class MyClient(discord.Client):
# If we want to do something in case of errors we'd do it here.
pass
intents = discord.Intents(guilds=True, members=True, guild_reactions=True)
client = MyClient(intents=intents)
client.run('token')
client.run("token")

View File

@ -1,17 +1,19 @@
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('!hello'):
await message.reply('Hello!', mention_author=True)
if message.content.startswith("!hello"):
await message.reply("Hello!", mention_author=True)
client = MyClient(intents=discord.Intents(guilds=True, messages=True))
client.run('token')
client.run("token")

View File

@ -6,18 +6,19 @@ from discord.ext import commands
bot = commands.Bot(
command_prefix=commands.when_mentioned,
description="Nothing to see here!",
intents=discord.Intents(guilds=True, messages=True)
intents=discord.Intents(guilds=True, messages=True),
)
# the `hidden` keyword argument hides it from the help command.
# the `hidden` keyword argument hides it from the help command.
@bot.group(hidden=True)
async def secret(ctx: commands.Context):
"""What is this "secret" you speak of?"""
if ctx.invoked_subcommand is None:
await ctx.send('Shh!', delete_after=5)
await ctx.send("Shh!", delete_after=5)
def create_overwrites(ctx, *objects):
"""This is just a helper function that creates the overwrites for the
"""This is just a helper function that creates the overwrites for the
voice/text channels.
A `discord.PermissionOverwrite` allows you to determine the permissions
@ -30,10 +31,7 @@ def create_overwrites(ctx, *objects):
# a dict comprehension is being utilised here to set the same permission overwrites
# for each `discord.Role` or `discord.Member`.
overwrites = {
obj: discord.PermissionOverwrite(view_channel=True)
for obj in objects
}
overwrites = {obj: discord.PermissionOverwrite(view_channel=True) for obj in objects}
# prevents the default role (@everyone) from viewing the channel
# if it isn't already allowed to view the channel.
@ -44,24 +42,26 @@ def create_overwrites(ctx, *objects):
return overwrites
# since these commands rely on guild related features,
# it is best to lock it to be guild-only.
@secret.command()
@commands.guild_only()
async def text(ctx: commands.Context, name: str, *objects: typing.Union[discord.Role, discord.Member]):
"""This makes a text channel with a specified name
"""This makes a text channel with a specified name
that is only visible to roles or members that are specified.
"""
overwrites = create_overwrites(ctx, *objects)
await ctx.guild.create_text_channel(
name,
overwrites=overwrites,
topic='Top secret text channel. Any leakage of this channel may result in serious trouble.',
reason='Very secret business.',
topic="Top secret text channel. Any leakage of this channel may result in serious trouble.",
reason="Very secret business.",
)
@secret.command()
@commands.guild_only()
async def voice(ctx: commands.Context, name: str, *objects: typing.Union[discord.Role, discord.Member]):
@ -71,11 +71,8 @@ async def voice(ctx: commands.Context, name: str, *objects: typing.Union[discord
overwrites = create_overwrites(ctx, *objects)
await ctx.guild.create_voice_channel(
name,
overwrites=overwrites,
reason='Very secret business.'
)
await ctx.guild.create_voice_channel(name, overwrites=overwrites, reason="Very secret business.")
@secret.command()
@commands.guild_only()
@ -89,12 +86,7 @@ async def emoji(ctx: commands.Context, emoji: discord.PartialEmoji, *roles: disc
# the key parameter here is `roles`, which controls
# what roles are able to use the emoji.
await ctx.guild.create_custom_emoji(
name=emoji.name,
image=emoji_bytes,
roles=roles,
reason='Very secret business.'
)
await ctx.guild.create_custom_emoji(name=emoji.name, image=emoji_bytes, roles=roles, reason="Very secret business.")
bot.run('token')
bot.run("token")

View File

@ -6,13 +6,12 @@ import discord
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
# Define a simple View that gives us a confirmation menu
@ -24,16 +23,16 @@ class Confirm(discord.ui.View):
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Confirming', ephemeral=True)
await interaction.response.send_message("Confirming", ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.grey)
async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Cancelling', ephemeral=True)
await interaction.response.send_message("Cancelling", ephemeral=True)
self.value = False
self.stop()
@ -46,15 +45,15 @@ async def ask(ctx: commands.Context):
"""Asks the user a question to confirm something."""
# We create the view and assign it to a variable so we can wait for it later.
view = Confirm()
await ctx.send('Do you want to continue?', view=view)
await ctx.send("Do you want to continue?", view=view)
# Wait for the View to stop listening for input...
await view.wait()
if view.value is None:
print('Timed out...')
print("Timed out...")
elif view.value:
print('Confirmed...')
print("Confirmed...")
else:
print('Cancelled...')
print("Cancelled...")
bot.run('token')
bot.run("token")

View File

@ -6,13 +6,12 @@ import discord
class CounterBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
# Define a simple View that gives us a counter button
@ -22,7 +21,7 @@ class Counter(discord.ui.View):
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label='0', style=discord.ButtonStyle.red)
@discord.ui.button(label="0", style=discord.ButtonStyle.red)
async def count(self, button: discord.ui.Button, interaction: discord.Interaction):
number = int(button.label) if button.label else 0
if number + 1 >= 5:
@ -40,7 +39,7 @@ bot = CounterBot()
@bot.command()
async def counter(ctx: commands.Context):
"""Starts a counter for pressing."""
await ctx.send('Press!', view=Counter())
await ctx.send("Press!", view=Counter())
bot.run('token')
bot.run("token")

View File

@ -9,22 +9,22 @@ class Dropdown(discord.ui.Select):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦')
discord.SelectOption(label="Red", description="Your favourite colour is red", emoji="🟥"),
discord.SelectOption(label="Green", description="Your favourite colour is green", emoji="🟩"),
discord.SelectOption(label="Blue", description="Your favourite colour is blue", emoji="🟦"),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
super().__init__(placeholder="Choose your favourite colour...", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
await interaction.response.send_message(f"Your favourite colour is {self.values[0]}")
class DropdownView(discord.ui.View):
@ -38,15 +38,14 @@ class DropdownView(discord.ui.View):
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
bot = Bot()
@ -58,7 +57,7 @@ async def colour(ctx):
view = DropdownView()
# Sending a message containing our view
await ctx.send('Pick your favourite colour:', view=view)
await ctx.send("Pick your favourite colour:", view=view)
bot.run('token')
bot.run("token")

View File

@ -2,16 +2,17 @@ from discord.ext import commands
import discord
class EphemeralCounterBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
# Define a simple View that gives us a counter button
class Counter(discord.ui.View):
@ -20,7 +21,7 @@ class Counter(discord.ui.View):
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label='0', style=discord.ButtonStyle.red)
@discord.ui.button(label="0", style=discord.ButtonStyle.red)
async def count(self, button: discord.ui.Button, interaction: discord.Interaction):
number = int(button.label) if button.label else 0
if number + 1 >= 5:
@ -31,20 +32,24 @@ class Counter(discord.ui.View):
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)
# Define a View that will give us our own personal counter button
class EphemeralCounter(discord.ui.View):
# When this button is pressed, it will respond with a Counter view that will
# give the button presser their own personal button they can press 5 times.
@discord.ui.button(label='Click', style=discord.ButtonStyle.blurple)
@discord.ui.button(label="Click", style=discord.ButtonStyle.blurple)
async def receive(self, button: discord.ui.Button, interaction: discord.Interaction):
# ephemeral=True makes the message hidden from everyone except the button presser
await interaction.response.send_message('Enjoy!', view=Counter(), ephemeral=True)
await interaction.response.send_message("Enjoy!", view=Counter(), ephemeral=True)
bot = EphemeralCounterBot()
@bot.command()
async def counter(ctx: commands.Context):
"""Starts a counter for pressing."""
await ctx.send('Press!', view=EphemeralCounter())
await ctx.send("Press!", view=EphemeralCounter())
bot.run('token')
bot.run("token")

View File

@ -3,16 +3,16 @@ from discord.ext import commands
import discord
from urllib.parse import quote_plus
class GoogleBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
# Define a simple View that gives us a google link button.
@ -22,12 +22,12 @@ class Google(discord.ui.View):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f'https://www.google.com/search?q={query}'
url = f"https://www.google.com/search?q={query}"
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))
self.add_item(discord.ui.Button(label="Click Here", url=url))
bot = GoogleBot()
@ -36,7 +36,7 @@ bot = GoogleBot()
@bot.command()
async def google(ctx: commands.Context, *, query: str):
"""Returns a google link for a query"""
await ctx.send(f'Google Result for: `{query}`', view=Google(query))
await ctx.send(f"Google Result for: `{query}`", view=Google(query))
bot.run()

View File

@ -14,24 +14,23 @@ class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
@discord.ui.button(label="Green", style=discord.ButtonStyle.green, custom_id="persistent_view:green")
async def green(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('This is green.', ephemeral=True)
await interaction.response.send_message("This is green.", ephemeral=True)
@discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
@discord.ui.button(label="Red", style=discord.ButtonStyle.red, custom_id="persistent_view:red")
async def red(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('This is red.', ephemeral=True)
await interaction.response.send_message("This is red.", ephemeral=True)
@discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
@discord.ui.button(label="Grey", style=discord.ButtonStyle.grey, custom_id="persistent_view:grey")
async def grey(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('This is grey.', ephemeral=True)
await interaction.response.send_message("This is grey.", ephemeral=True)
class PersistentViewBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
self.persistent_views_added = False
@ -46,8 +45,8 @@ class PersistentViewBot(commands.Bot):
self.add_view(PersistentView())
self.persistent_views_added = True
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
bot = PersistentViewBot()
@ -64,4 +63,4 @@ async def prepare(ctx: commands.Context):
await ctx.send("What's your favourite colour?", view=PersistentView())
bot.run('token')
bot.run("token")

View File

@ -5,13 +5,13 @@ import discord
# Defines a custom button that contains the logic of the game.
# The ['TicTacToe'] bit is for type hinting purposes to tell your IDE or linter
# what the type of `self.view` is. It is not required.
class TicTacToeButton(discord.ui.Button['TicTacToe']):
class TicTacToeButton(discord.ui.Button["TicTacToe"]):
def __init__(self, x: int, y: int):
# A label is required, but we don't need one so a zero-width space is used
# The row parameter tells the View which row to place the button under.
# A View can only contain up to 5 rows -- each row can only have 5 buttons.
# Since a Tic Tac Toe grid is 3x3 that means we have 3 rows and 3 columns.
super().__init__(style=discord.ButtonStyle.secondary, label='\u200b', row=y)
super().__init__(style=discord.ButtonStyle.secondary, label="\u200b", row=y)
self.x = x
self.y = y
@ -26,14 +26,14 @@ class TicTacToeButton(discord.ui.Button['TicTacToe']):
if view.current_player == view.X:
self.style = discord.ButtonStyle.danger
self.label = 'X'
self.label = "X"
self.disabled = True
view.board[self.y][self.x] = view.X
view.current_player = view.O
content = "It is now O's turn"
else:
self.style = discord.ButtonStyle.success
self.label = 'O'
self.label = "O"
self.disabled = True
view.board[self.y][self.x] = view.O
view.current_player = view.X
@ -42,9 +42,9 @@ class TicTacToeButton(discord.ui.Button['TicTacToe']):
winner = view.check_board_winner()
if winner is not None:
if winner == view.X:
content = 'X won!'
content = "X won!"
elif winner == view.O:
content = 'O won!'
content = "O won!"
else:
content = "It's a tie!"
@ -121,13 +121,12 @@ class TicTacToe(discord.ui.View):
class TicTacToeBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('$'),
intents=discord.Intents(guilds=True, messages=True)
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
bot = TicTacToeBot()
@ -136,7 +135,7 @@ bot = TicTacToeBot()
@bot.command()
async def tic(ctx: commands.Context):
"""Starts a tic-tac-toe game with yourself."""
await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())
await ctx.send("Tic Tac Toe: X goes first", view=TicTacToe())
bot.run('token')
bot.run("token")