Skip to content

Commit

Permalink
Pin Serenity to version 0.11.1 & bump our version (#143)
Browse files Browse the repository at this point in the history
* Implement Serenity 0.11.1 changes

* Version bump

* Restore prefix & GUILD_MESSAGES intent
  • Loading branch information
Headline committed Apr 20, 2022
1 parent 80a615b commit 99f43d8
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 50 deletions.
7 changes: 3 additions & 4 deletions Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "discord-compiler-bot"
description = "Discord bot to compile your spaghetti code."
version = "3.3.2"
version = "3.3.3"
authors = ["Michael Flaherty (Headline#9999)"]
edition = "2018"
build = "src/build.rs"
Expand Down Expand Up @@ -32,9 +32,8 @@ chrono = "0.4.19"


[dependencies.serenity]
version = "0.10"
rev = "9624af0def9cd191a51750232edce23970486a0e"
git = "https://github.com/serenity-rs/serenity"
version = "0.11"
#git = "https://github.com/serenity-rs/serenity"
#branch = "current"
default-features = false
features = ["collector", "gateway", "builder", "standard_framework", "http", "model", "client", "framework", "utils", "rustls_backend", "unstable_discord_api"]
Expand Down
12 changes: 12 additions & 0 deletions discord-compiler.iml
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="RUST_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
3 changes: 1 addition & 2 deletions src/cache.rs
Expand Up @@ -7,7 +7,6 @@ use tokio::sync::RwLock;
use tokio::sync::Mutex;

use serenity::prelude::{TypeMap, TypeMapKey};
use serenity::model::id::UserId;
use serenity::client::bridge::gateway::ShardManager;

use crate::managers::stats::StatsManager;
Expand Down Expand Up @@ -85,7 +84,7 @@ impl TypeMapKey for CommandCache {
pub async fn fill(
data: Arc<RwLock<TypeMap>>,
prefix: &str,
id: &UserId,
id: u64,
shard_manager: Arc<tokio::sync::Mutex<ShardManager>>
) -> Result<(), Box<dyn Error>> {
let mut data = data.write().await;
Expand Down
2 changes: 1 addition & 1 deletion src/commands/asm.rs
Expand Up @@ -25,7 +25,7 @@ pub async fn asm(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
.await?;

// Success/fail react
let compilation_successful = asm_embed.embeds[0].colour.0 == COLOR_OKAY;
let compilation_successful = asm_embed.embeds[0].colour.unwrap().0 == COLOR_OKAY;
discordhelpers::send_completion_react(ctx, &asm_embed, compilation_successful).await?;

let data_read = ctx.data.read().await;
Expand Down
2 changes: 1 addition & 1 deletion src/commands/compile.rs
Expand Up @@ -32,7 +32,7 @@ pub async fn compile(ctx: &Context, msg: &Message, _args: Args) -> CommandResult
.await?;

// Success/fail react
let compilation_successful = compilation_embed.embeds[0].colour.0 == COLOR_OKAY;
let compilation_successful = compilation_embed.embeds[0].colour.unwrap().0 == COLOR_OKAY;
discordhelpers::send_completion_react(ctx, &compilation_embed, compilation_successful).await?;

let mut delete_cache = data_read.get::<MessageCache>().unwrap().lock().await;
Expand Down
24 changes: 8 additions & 16 deletions src/events.rs
Expand Up @@ -5,7 +5,6 @@ use serenity::{
async_trait,
model::channel::Message,
model::guild::Guild,
model::guild::GuildUnavailable,
model::id::ChannelId,
model::id::MessageId,
model::gateway::Ready,
Expand All @@ -16,10 +15,11 @@ use serenity::{
collector::CollectReaction,
model::interactions::{Interaction}
};
use serenity::model::prelude::UnavailableGuild;

use tokio::sync::MutexGuard;

use chrono::{DateTime, Duration, Utc};
use chrono::{DateTime, Utc};

use crate::{
utls::discordhelpers::embeds,
Expand Down Expand Up @@ -64,7 +64,7 @@ impl EventHandler for Handler {
let data = ctx.data.read().await;

let now: DateTime<Utc> = Utc::now();
if guild.joined_at + Duration::seconds(30) > now {
if guild.joined_at.unix_timestamp() + 30 > now.timestamp() {
// post new server to join log
let id;
{
Expand Down Expand Up @@ -107,27 +107,19 @@ impl EventHandler for Handler {
let mut message = embeds::embed_message(embeds::build_welcome_embed());
let _ = system_channel.send_message(&ctx.http, |_| &mut message).await;
}
else {
for (_, channel) in guild.channels {
if channel.name.contains("general") {
let mut message = embeds::embed_message(embeds::build_welcome_embed());
let _ = channel.send_message(&ctx.http, |_| &mut message).await;
}
}
}
}
}

async fn guild_delete(&self, ctx: Context, incomplete: GuildUnavailable) {
async fn guild_delete(&self, ctx: Context, incomplete: UnavailableGuild) {
let data = ctx.data.read().await;

// post new server to join log
let info = data.get::<ConfigCache>().unwrap().read().await;
let id = info.get("BOT_ID").unwrap().parse::<u64>().unwrap();
let id = info.get("BOT_ID").unwrap().parse::<u64>().unwrap(); // used later
if let Some(log) = info.get("JOIN_LOG") {
if let Ok(id) = log.parse::<u64>() {
if let Ok(join_id) = log.parse::<u64>() {
let emb = embeds::build_leave_embed(&incomplete.id);
discordhelpers::manual_dispatch(ctx.http.clone(), id, emb).await;
discordhelpers::manual_dispatch(ctx.http.clone(), join_id, emb).await;
}
}

Expand Down Expand Up @@ -366,7 +358,7 @@ pub async fn after(
}

#[hook]
pub async fn dispatch_error(ctx: &Context, msg: &Message, error: DispatchError) {
pub async fn dispatch_error(ctx: &Context, msg: &Message, error: DispatchError, _: &str) {
if let DispatchError::Ratelimited(_) = error {
let emb =
embeds::build_fail_embed(&msg.author, "You are sending requests too fast!");
Expand Down
25 changes: 16 additions & 9 deletions src/main.rs
Expand Up @@ -12,12 +12,13 @@ mod tests;
mod slashcmds;

use serenity::{
client::bridge::gateway::GatewayIntents,
framework::{standard::macros::group, StandardFramework},
http::Http,
};

use std::{collections::HashSet, env, error::Error};
use std::{env, error::Error};
use std::collections::HashSet;
use serenity::http::Http;
use serenity::prelude::GatewayIntents;

use crate::apis::dbl::BotsListApi;

Expand Down Expand Up @@ -47,7 +48,8 @@ async fn main() -> Result<(), Box<dyn Error>> {

let token = env::var("BOT_TOKEN")
.expect("Expected bot token in .env file");
let http = Http::new_with_token(&token);

let http = Http::new(&token);
let (owners, bot_id) = match http.get_current_application_info().await {
Ok(info) => {
let mut owners = HashSet::new();
Expand All @@ -69,7 +71,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
.expect("Unable to find BOT_ID environment variable");
let bot_id = id.parse::<u64>()
.expect("Invalid bot id");
(HashSet::new(), serenity::model::id::UserId(bot_id))
(HashSet::new(), serenity::model::id::ApplicationId(bot_id))
},
};

Expand All @@ -87,21 +89,26 @@ async fn main() -> Result<(), Box<dyn Error>> {
let app_id = env::var("APPLICATION_ID")
.expect("Expected application id in .env file");
let framework = StandardFramework::new()
.configure(|c| c.owners(owners).prefix(&prefix))
.before(events::before)
.after(events::after)
.configure(|c| c.owners(owners).prefix(&prefix))
.group(&GENERAL_GROUP)
.bucket("nospam", |b| b.delay(3).time_span(10).limit(3))
.await
.on_dispatch_error(events::dispatch_error);
let mut client = serenity::Client::builder(token)

let intents = GatewayIntents::GUILDS
| GatewayIntents::MESSAGE_CONTENT
| GatewayIntents::GUILD_INTEGRATIONS
| GatewayIntents::GUILD_MESSAGE_REACTIONS
| GatewayIntents::GUILD_MESSAGES;
let mut client = serenity::Client::builder(token,intents)
.framework(framework)
.event_handler(events::Handler)
.intents(GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::GUILD_MESSAGE_REACTIONS)
.application_id(app_id.parse::<u64>().unwrap())
.await?;

cache::fill(client.data.clone(), &prefix, &bot_id, client.shard_manager.clone()).await?;
cache::fill(client.data.clone(), &prefix, bot_id.0, client.shard_manager.clone()).await?;

let dbl = BotsListApi::new();
if dbl.should_spawn() {
Expand Down
17 changes: 9 additions & 8 deletions src/slashcmds/format.rs
Expand Up @@ -39,10 +39,11 @@ pub async fn format(ctx: &Context, command: &ApplicationCommandInteraction) -> C

// Handle response from select menu / button interactions
let resp = command.get_interaction_response(&ctx.http).await?;
let mut cib = resp.await_component_interactions(&ctx.shard).timeout(Duration::from_secs(30)).await;
let mut cib = resp.await_component_interactions(&ctx.shard).timeout(Duration::from_secs(30));
let mut cic = cib.build();
let mut formatter = String::from("clangformat");
let mut selected = false;
while let Some(interaction) = &cib.next().await {
while let Some(interaction) = &cic.next().await {
match interaction.data.custom_id.as_str() {
"formatter" => {
formatter = interaction.data.values[0].clone();
Expand All @@ -51,7 +52,7 @@ pub async fn format(ctx: &Context, command: &ApplicationCommandInteraction) -> C
"select" => {
interaction.defer(&ctx.http).await?;
selected = true;
cib.stop();
cic.stop();
break;
}
_ => {
Expand All @@ -71,19 +72,19 @@ pub async fn format(ctx: &Context, command: &ApplicationCommandInteraction) -> C
}).await?;

let resp = command.get_interaction_response(&ctx.http).await?;
cib = resp.await_component_interactions(&ctx.shard).timeout(Duration::from_secs(30)).await;

cib = resp.await_component_interactions(&ctx.shard).timeout(Duration::from_secs(30));
cic = cib.build();
selected = false;
let mut style = String::from("WebKit");
while let Some(interaction) = &cib.next().await {
while let Some(interaction) = &cic.next().await {
match interaction.data.custom_id.as_str() {
"style" => {
style = interaction.data.values[0].clone();
interaction.defer(&ctx.http).await?;
}
"select" => {
selected = true;
cib.stop();
cic.stop();
break;
}
_ => {
Expand Down Expand Up @@ -166,7 +167,7 @@ fn create_styles_interaction<'a>(response: &'a mut EditInteractionResponse, styl
})
}

fn create_formats_interaction<'a>(response: &'a mut CreateInteractionResponse, formats: &Vec<Format>) -> &'a mut CreateInteractionResponse {
fn create_formats_interaction<'this,'a>(response: &'this mut CreateInteractionResponse<'a>, formats: &Vec<Format>) -> &'this mut CreateInteractionResponse<'a> {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|data| {
Expand Down
13 changes: 7 additions & 6 deletions src/utls/discordhelpers/interactions.rs
Expand Up @@ -208,7 +208,7 @@ pub fn edit_to_confirmation_interaction<'a>(result: &CreateEmbed, resp: &'a mut
})
}

pub fn create_language_interaction<'a>(resp : &'a mut CreateInteractionResponse, languages : &[&str]) -> &'a mut CreateInteractionResponse {
pub fn create_language_interaction<'this, 'a>(resp : &'this mut CreateInteractionResponse<'a>, languages : & [&str]) -> &'this mut CreateInteractionResponse<'a> {
resp
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|data| {
Expand All @@ -235,7 +235,7 @@ pub fn create_language_interaction<'a>(resp : &'a mut CreateInteractionResponse,
})
}

pub fn create_dismiss_response(resp: &mut CreateInteractionResponse) -> &mut CreateInteractionResponse {
pub fn create_dismiss_response<'this, 'a>(resp: &'this mut CreateInteractionResponse<'a>) -> &'this mut CreateInteractionResponse<'a> {
resp
.kind(InteractionResponseType::UpdateMessage)
.interaction_response_data(|data| {
Expand Down Expand Up @@ -335,14 +335,15 @@ where
}

let resp = command.get_interaction_response(&ctx.http).await?;
let mut cib = resp.await_component_interactions(&ctx.shard).timeout(Duration::from_secs(30)).await;
let cib = resp.await_component_interactions(&ctx.shard).timeout(Duration::from_secs(30));
let mut cic = cib.build();

// collect compiler into var
parse_result.target = language.to_owned();

let mut last_interaction = None;
let mut more_options_response = None;
while let Some(interaction) = &cib.next().await {
while let Some(interaction) = &cic.next().await {
last_interaction = Some(interaction.clone());
match interaction.data.custom_id.as_str() {
"compiler_select" => {
Expand All @@ -364,12 +365,12 @@ where

more_options_response = create_more_options_panel(ctx, interaction.clone(), & mut parse_result).await?;
if more_options_response.is_some() {
cib.stop();
cic.stop();
break;
}
}
"1" => {
cib.stop();
cic.stop();
break;
}
_ => {
Expand Down
6 changes: 4 additions & 2 deletions src/utls/discordhelpers/menu.rs
Expand Up @@ -31,8 +31,10 @@ impl Menu {
.set_components(self.components.clone())
}).await?;

let mut cib = m.await_component_interactions(&self.ctx.shard).timeout(Duration::from_secs(60)).await;
while let Some(int) = cib.next().await {
let cib = m.await_component_interactions(&self.ctx.shard)
.timeout(Duration::from_secs(60));
let mut cic = cib.build();
while let Some(int) = cic.next().await {
match int.data.custom_id.as_str() {
"left" => {
if self.page > 0 {
Expand Down
2 changes: 1 addition & 1 deletion src/utls/discordhelpers/mod.rs
Expand Up @@ -155,7 +155,7 @@ pub async fn send_completion_react(ctx: &Context, msg: &Message, success: bool)
let botinfo = botinfo_lock.read().await;
if let Some(success_id) = botinfo.get("SUCCESS_EMOJI_ID") {
let success_name = botinfo.get("SUCCESS_EMOJI_NAME").expect("Unable to find success emoji name").clone();
reaction = discordhelpers::build_reaction(success_id.parse::<u64>()?, &success_name);
reaction = discordhelpers::build_reaction(success_id.parse::<u64>().unwrap(), &success_name);
}
else {
reaction = ReactionType::Unicode(String::from("✅"));
Expand Down

0 comments on commit 99f43d8

Please sign in to comment.