write a app in rust and use serenity and poise to make it discord bot and is organized
add a command that will get a tenor link or name (then search in tenor) then edit the image and add the requested text on top of it
use serde yaml for config
Assistant
Creating a well-organized Discord bot in Rust using the Serenity and Poise libraries involves structuring your project into modules, handling configuration with serde_yaml, interacting with the Tenor API, and performing image manipulation to add text overlays. Below is a comprehensive guide to help you set up such a bot.
Project Structure
Here's a recommended project structure to keep your code organized:
Create an image_utils.rs module to handle image downloading and text overlay:
rust
// src/image_utils.rs
use image::{DynamicImage, ImageFormat, Rgba};
use imageproc::drawing::draw_text_mut;
use rusttype::{Font, Scale};
use reqwest::Client;
use std::error::Error;
use std::io::Cursor;
pub struct ImageUtils {
client: Client,
font: Font<'static>,
}
impl ImageUtils {
pub fn new() -> Result<Self, Box<dyn Error>> {
// Include a font file (e.g., DejaVuSans)
let font_data: &[u8] = include_bytes!("../fonts/DejaVuSans.ttf");
let font = Font::try_from_bytes(font_data).ok_or("Font error")?;
Ok(ImageUtils {
client: Client::new(),
font,
})
}
pub async fn download_image(&self, url: &str) -> Result<DynamicImage, Box<dyn Error>> {
let resp = self.client.get(url).send().await?.bytes().await?;
let img = image::load(Cursor::new(resp), ImageFormat::Png)?;
Ok(img)
}
pub fn add_text(
&self,
mut img: DynamicImage,
text: &str,
) -> Result<DynamicImage, Box<dyn Error>> {
let mut img = img.to_rgba8();
let scale = Scale {
x: 40.0,
y: 40.0,
};
let color = Rgba([255, 255, 255, 255]);
let position = (10, 10); // Top-left corner
draw_text_mut(&mut img, color, position.0, position.1, scale, &self.font, text);
Ok(DynamicImage::ImageRgba8(img))
}
pub fn encode_image(&self, img: &DynamicImage) -> Result<Vec<u8>, Box<dyn Error>> {
let mut buf = Vec::new();
img.write_to(&mut Cursor::new(&mut buf), ImageFormat::Png)?;
Ok(buf)
}
}
Note: You'll need to include a .ttf font file in a fonts/ directory within your project root. For example, place DejaVuSans.ttf in fonts/DejaVuSans.ttf. Ensure the path in include_bytes! matches.
5. Defining Commands with Poise
Create a commands.rs module to define your bot commands:
rust
// src/commands.rs
use poise::serenity_prelude as serenity;
use crate::{Config, Tenor, ImageUtils};
use poise::CommandResult;
#[poise::command(
prefix_command,
slash_command,
description = "Fetches an image from Tenor and adds text on top."
)]
pub async fn meme(
ctx: poise::Context<'_>,
#[description = "Tenor search term or URL"] query: String,
#[description = "Text to add on the image"] text: String,
) -> CommandResult {
let data = ctx.data();
let tenor = data.tenor.as_ref().unwrap();
let image_utils = data.image_utils.as_ref().unwrap();
// Determine if the query is a URL or search term
let image_url = if query.starts_with("http") {
query
} else {
tenor.search(&query).await?
};
// Download and process the image
let img = image_utils.download_image(&image_url).await?;
let img_with_text = image_utils.add_text(img, &text)?;
let encoded = image_utils.encode_image(&img_with_text)?;
// Send the image back
let attachment = serenity::AttachmentType::from_bytes(encoded, "meme.png");
ctx.send(|m| m.add_file(attachment)).await?;
Ok(())
}
6. Shared Data State
Define a structure to hold shared data like the Tenor API client and ImageUtils:
rust
// src/main.rs
mod commands;
mod config;
mod image_utils;
mod tenor;
use config::Config;
use image_utils::ImageUtils;
use poise::Framework;
use serenity::async_trait;
use serenity::Client;
use std::sync::Arc;
struct Data {
tenor: Option<Tenor>,
image_utils: Option<ImageUtils>,
}
#[tokio::main]
async fn main() {
// Load configuration
let config = Config::from_file("config.yaml").expect("Failed to load configuration");
// Initialize Tenor and ImageUtils
let tenor = Tenor::new(config.tenor_api_key.clone());
let image_utils = ImageUtils::new().expect("Failed to initialize ImageUtils");
let data = Data {
tenor: Some(tenor),
image_utils: Some(image_utils),
};
// Build the framework
let framework = Framework::build()
.token(&config.token)
.intents(serenity::GatewayIntents::all())
.options(poise::FrameworkOptions {
commands: vec![commands::meme()],
..Default::default()
})
.setup(move |_ctx, _ready, _framework| {
Box::pin(async move {
// Share the data
Ok(Arc::new(data))
})
});
// Start the bot
framework.run().await.unwrap();
}
7. Handling Shared State in Commands
Modify your commands.rs to access the shared data:
rust
// src/commands.rs
use poise::serenity_prelude as serenity;
use crate::{Config, Tenor, ImageUtils, Data};
use poise::CommandResult;
#[poise::command(
prefix_command,
slash_command,
description = "Fetches an image from Tenor and adds text on top."
)]
pub async fn meme(
ctx: poise::Context<'_>,
#[description = "Tenor search term or URL"] query: String,
#[description = "Text to add on the image"] text: String,
) -> CommandResult {
let data = ctx.data();
let tenor = data.tenor.as_ref().unwrap();
let image_utils = data.image_utils.as_ref().unwrap();
// Determine if the query is a URL or search term
let image_url = if query.starts_with("http") {
query
} else {
tenor.search(&query).await?
};
// Download and process the image
let img = image_utils.download_image(&image_url).await?;
let img_with_text = image_utils.add_text(img, &text)?;
let encoded = image_utils.encode_image(&img_with_text)?;
// Send the image back
let attachment = serenity::AttachmentType::from_bytes(encoded, "meme.png");
ctx.send(|m| m.add_file(attachment)).await?;
Ok(())
}
Ensure that the Data struct is accessible in the commands.rs module or adjust the access accordingly.
8. Error Handling and Enhancements
For production-ready code, you should add comprehensive error handling, logging, and possibly rate-limiting to handle API usage limits. Additionally, consider caching frequent Tenor queries to improve performance and reduce API calls.
Running the Bot
Environment Setup:
Ensure you have Rust installed. If not, install it from rustup.rs.
Fonts: Ensure the font file (DejaVuSans.ttf in the example) exists in the specified path. You can use any .ttf font, but make sure you have the rights to use it.
Concurrency: The ImageUtils and Tenor instances are shared across commands. If you plan to add more state or handle concurrent modifications, consider using synchronization primitives like Mutex or RwLock.
Extending Functionality: You can add more commands by following the structure in commands.rs. Poise makes it straightforward to define both prefix and slash commands.
Logging: Integrate a logging library like tracing or log to output debug information, which is invaluable for diagnosing issues.
Conclusion
This guide provides a structured approach to building a Discord bot in Rust that interacts with the Tenor API and performs image manipulation. By organizing your code into modules and handling configurations through serde_yaml, you ensure maintainability and scalability. Feel free to extend the bot's functionality by adding more features and commands as needed.