Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace current v2 examples to lightbulb v3 syntax #436

Merged
merged 3 commits into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 38 additions & 25 deletions examples/basic_bot_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,52 @@

import lightbulb

bot = lightbulb.BotApp(prefix="!", token="YOUR_TOKEN", intents=hikari.Intents.ALL_UNPRIVILEGED)
bot = hikari.GatewayBot(token="...")
client = lightbulb.client_from_app(bot)

bot.subscribe(hikari.StartingEvent, client.start)

@bot.listen(hikari.ShardReadyEvent)
async def ready_listener(_):
print("The bot is ready!")

@client.register()
class Ping(
lightbulb.SlashCommand,
name="ping",
description="Checks that the bot is alive",
):
@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Checks that the bot is alive"""
await ctx.respond("Pong!")

@bot.command()
@lightbulb.command("ping", "Checks that the bot is alive")
@lightbulb.implements(lightbulb.PrefixCommand)
async def ping(ctx: lightbulb.Context) -> None:
"""Checks that the bot is alive"""
await ctx.respond("Pong!")

@client.register()
class Echo(
lightbulb.SlashCommand,
name="echo",
description="Repeats the user's input",
):
text = lightbulb.string("text", "Text to repeat")

@bot.command()
@lightbulb.option("num2", "Second number", int)
@lightbulb.option("num1", "First number", int)
@lightbulb.command("add", "Adds the two given numbers together")
@lightbulb.implements(lightbulb.PrefixCommand)
async def add(ctx: lightbulb.Context) -> None:
"""Adds the two given numbers together"""
num1, num2 = ctx.options.num1, ctx.options.num2
await ctx.respond(f"{num1} + {num2} = {num1 + num2}")
@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Repeats the user's input"""
await ctx.respond(self.text)


@bot.command()
@lightbulb.option("user", "User to greet", hikari.User)
@lightbulb.command("greet", "Greets the specified user")
@lightbulb.implements(lightbulb.PrefixCommand)
async def greet(ctx: lightbulb.Context) -> None:
await ctx.respond(f"Hello {ctx.options.user.mention}!")
@client.register()
class Add(
lightbulb.SlashCommand,
name="add",
description="Adds the two given numbers together",
):
# Order of options go from top to bottom
num1 = lightbulb.integer("num1", "First number")
num2 = lightbulb.integer("num2", "Second number")

@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Adds the two given numbers together"""
await ctx.respond(f"{self.num1} + {self.num2} = {self.num1 + self.num2}")


bot.run()
39 changes: 0 additions & 39 deletions examples/basic_slash_command_bot_example.py

This file was deleted.

26 changes: 12 additions & 14 deletions examples/extension_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,18 @@
# along with Lightbulb. If not, see <https://www.gnu.org/licenses/>.
import lightbulb

example_plugin = lightbulb.Plugin("ExamplePlugin")
loader = lightbulb.Loader()


@example_plugin.command()
@lightbulb.command("ping", "Checks that the bot is alive")
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def ping(ctx: lightbulb.Context) -> None:
"""Checks that the bot is alive"""
await ctx.respond("Pong!")
@loader.command
class Greet(
lightbulb.SlashCommand,
name="greet",
description="Greets the specified user",
):
user = lightbulb.user("user", "User to greet")


def load(bot):
bot.add_plugin(example_plugin)


def unload(bot):
bot.remove_plugin(example_plugin)
@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Greets the specified user"""
await ctx.respond(f"Hello, {self.user.mention}!")
54 changes: 30 additions & 24 deletions examples/in_depth_component_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
}


async def generate_rows(bot: lightbulb.BotApp) -> t.Iterable[MessageActionRowBuilder]:
async def generate_rows(bot: hikari.GatwayBot) -> t.Iterable[MessageActionRowBuilder]:
"""Generate 2 action rows with 4 buttons each."""

# This will hold our action rows of buttons. The limit
Expand Down Expand Up @@ -103,7 +103,7 @@ async def generate_rows(bot: lightbulb.BotApp) -> t.Iterable[MessageActionRowBui


async def handle_responses(
bot: lightbulb.BotApp,
bot: hikari.GatewayBot,
author: hikari.User,
message: hikari.Message,
) -> None:
Expand Down Expand Up @@ -180,29 +180,35 @@ async def handle_responses(


# Instantiate the bot.
bot = lightbulb.BotApp(token="YOUR_TOKEN", prefix="!")


# Create the message command.
@bot.command()
@lightbulb.command("rgb", "Get facts on different colors!", guilds=[1234])
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def rgb_command(ctx: lightbulb.Context) -> None:
"""Get facts on different colors!"""

# Generate the action rows.
rows = await generate_rows(ctx.bot)

# Send the initial response with our action rows, and save the
# message for handling interaction responses.
response = await ctx.respond(
hikari.Embed(title="Pick a color"),
components=rows,
)
message = await response.message()
bot = hikari.GatewayBot(token="...")
client = lightbulb.client_from_app(bot)
# Ensure the client starts once the bot is run
bot.subscribe(hikari.StartingEvent, client.start)


@client.register(guilds=[1234])
tandemdude marked this conversation as resolved.
Show resolved Hide resolved
class RGB(
lightbulb.SlashCommand,
name="rgb",
description="Get facts on different colors!",
):
@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Get facts on different colors!"""

# Generate the action rows.
rows = await generate_rows(ctx.bot)
tandemdude marked this conversation as resolved.
Show resolved Hide resolved

# Send the initial response with our action rows, and save the
# message for handling interaction responses.
response = await ctx.respond(
hikari.Embed(title="Pick a color"),
components=rows,
)
message = await response.message()

# Handle interaction responses to the initial message.
await handle_responses(ctx.bot, ctx.author, message)
# Handle interaction responses to the initial message.
await handle_responses(ctx.bot, ctx.author, message)


# Run the bot.
Expand Down
96 changes: 57 additions & 39 deletions examples/moderation_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,51 +21,69 @@

import lightbulb

bot = lightbulb.BotApp(token="YOUR_TOKEN", intents=hikari.Intents.ALL_UNPRIVILEGED)
bot = hikari.GatewayBot(token="...")
client = lightbulb.client_from_app(bot)

bot.subscribe(hikari.StartingEvent, client.start)

@bot.command()
@lightbulb.option("reason", "Reason for the ban", required=False)
@lightbulb.option("user", "The user to ban.", type=hikari.User)
@lightbulb.command("ban", "Ban a user from the server.")
@lightbulb.implements(lightbulb.SlashCommand)
async def ban(ctx: lightbulb.SlashContext) -> None:
"""Ban a user from the server with an optional reason."""
if not ctx.guild_id:
await ctx.respond("This command can only be used in a guild.")
return

# Create a deferred response as the ban may take longer than 3 seconds
await ctx.respond(hikari.ResponseType.DEFERRED_MESSAGE_CREATE)
# Perform the ban
await ctx.app.rest.ban_user(ctx.guild_id, ctx.options.user.id, reason=ctx.options.reason or hikari.UNDEFINED)
# Provide feedback to the moderator
await ctx.respond(f"Banned {ctx.options.user.mention}.\n**Reason:** {ctx.options.reason or 'No reason provided.'}")
@client.register()
class Ban(
tandemdude marked this conversation as resolved.
Show resolved Hide resolved
lightbulb.SlashCommand,
name="ban",
description="Bans a user from the server",
):
# Order of options go from top to bottom
user = lightbulb.user("user", "The user to ban")
# Give non-required options a default value (e.g. default=None)
# Non-required options MUST appear after required options
# Required options do not have a default value
reason = lightbulb.string("reason", "Reason for the ban", default=None)

@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Ban a user from the server with an optional reason"""
if not ctx.guild_id:
await ctx.respond("This command can only be used in a guild.")
return

@bot.command()
@lightbulb.option("count", "The amount of messages to purge.", type=int, max_value=100, min_value=1)
# You may also use pass_options to pass the options directly to the function
@lightbulb.command("purge", "Purge a certain amount of messages from a channel.", pass_options=True)
@lightbulb.implements(lightbulb.SlashCommand)
async def purge(ctx: lightbulb.SlashContext, count: int) -> None:
"""Purge a certain amount of messages from a channel."""
if not ctx.guild_id:
await ctx.respond("This command can only be used in a server.")
return
# Create a deferred response as the ban may take longer than 3 seconds
await ctx.respond(hikari.ResponseType.DEFERRED_MESSAGE_CREATE)
# Perform the ban
await ctx.app.rest.ban_user(ctx.guild_id, self.user.id, reason=self.reason or hikari.UNDEFINED)
tandemdude marked this conversation as resolved.
Show resolved Hide resolved
# Provide feedback to the moderator
await ctx.respond(f"Banned {self.user.mention}.\n**Reason:** {self.reason or 'No reason provided.'}")

# Fetch messages that are not older than 14 days in the channel the command is invoked in
# Messages older than 14 days cannot be deleted by bots, so this is a necessary precaution
messages = (
await ctx.app.rest.fetch_messages(ctx.channel_id)
.take_until(lambda m: datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=14) > m.created_at)
.limit(count)
)
if messages:
await ctx.app.rest.delete_messages(ctx.channel_id, messages)
await ctx.respond(f"Purged {len(messages)} messages.")
else:
await ctx.respond("Could not find any messages younger than 14 days!")

@client.register()
class Purge(
lightbulb.SlashCommand,
name="purge",
description="Purge a certain amount of messages from a channel",
):
count = lightbulb.integer("count", "The amount of messages to purge", max_value=100, min_value=1)

@lightbulb.invoke
async def invoke(self, ctx: lightbulb.Context) -> None:
"""Purge a certain amount of messages from a channel"""
if not ctx.guild_id:
await ctx.respond("This command can only be used in a server.")
return

# Fetch messages that are not older than 14 days in the channel the command is invoked in
# Messages older than 14 days cannot be deleted by bots, so this is a necessary precaution
messages = (
await ctx.app.rest.fetch_messages(ctx.channel_id)
.take_until(
lambda m: datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=14) > m.created_at
)
.limit(self.count)
)
if messages:
await ctx.app.rest.delete_messages(ctx.channel_id, messages)
await ctx.respond(f"Purged {len(messages)} messages.")
else:
await ctx.respond("Could not find any messages younger than 14 days!")


bot.run()
35 changes: 0 additions & 35 deletions examples/plugin_example.py

This file was deleted.

Loading