Compare commits

...

12 Commits

Author SHA1 Message Date
poslop
0b3934e29f Merge branch 'main' of https://git.mintyserver.net/poslop/Mindustry-Server-Discord-Bot
done
2023-12-14 12:25:03 -06:00
poslop
da9822ef18 add cmd as an alias and added exit 0 2023-12-14 12:23:59 -06:00
poslop
98540a569a Update readme.md 2023-12-13 09:52:09 -06:00
poslop
c4abd033fc add cmd as an alias 2023-12-13 09:31:37 -06:00
poslop
2c28c6482e update llinks 2023-10-31 11:04:11 -05:00
poslop
702d77c4e8 reconneeeeeeect 2023-02-17 16:22:34 -06:00
poslop
db541c1e55 fixed bug of useing 100% cpu 2023-01-18 15:15:07 -06:00
poslop
0d932be721 include binary in git 2023-01-13 16:11:13 -06:00
poslop
6fa6c31581 fix search command 2023-01-13 16:09:09 -06:00
poslop
dbc72c0fd4 Merge branch 'main' of https://mintyserver.net/git/poslop/Mindustry-Server-Discord-Bot 2022-12-14 21:05:07 -06:00
poslop
80c233ab6f Update 'config.toml' 2022-12-08 00:26:13 -06:00
poslop
fd0213ecc0 Update 'config.toml' 2022-12-08 00:24:59 -06:00
6 changed files with 161 additions and 38 deletions

View File

@@ -16,10 +16,12 @@ port = "6859"
prefix = ";"
[admin_roles]
# These are the role ids needed in order to use the console command
# If an invalid role is used it will be ignored
# If all the roles are invalid or the list is empty the setting will be ignored
[admin_roles]
# people with roles ids in the owner setting can use all console commands
# if left empty anyone can use any of the commands
@@ -28,9 +30,12 @@ owners = ["738543444322156574", "822523680391037009"]
# list of admin roles
admins = []
# this controls which commands admins have access too
[console]
# these control which commands admins have access too
# whether the command list is a whitelist or a blacklist
# true = whitelist
# false = blacklist

View File

@@ -1,5 +1,5 @@
## Real git
### [**Gitea**](https://mintyserver.net/git/poslop/Mindustry-Server-Discord-Bot)
### [**Gitea**](https://git.mintyserver.net/poslop/Mindustry-Server-Discord-Bot)
> This is the actual git for this project where **Releases** for **Download** are made
@@ -18,6 +18,8 @@ Or you can download the [template](config.toml) from the git
Check the [template](config.toml) for details about each setting
Make sure your discord bot has the Presence Intent and Server Members Intent
## Commands
- **console:** used to send a command to the mindustry server console

View File

@@ -45,13 +45,12 @@ async fn normal_message(_ctx: &Context, msg: &Message) {
println!("Message is not a command '{}'", msg.content);
}
#[tokio::main]
async fn main() {
let conf = init_conf().await;
let sock = TcpSock::new(conf.discord_settings.ip.clone(), conf.discord_settings.port.clone()).unwrap();
let sock = TcpSock::new(conf.discord_settings.ip.clone(), conf.discord_settings.port.clone()).expect("tcp connection failed");
let framework = StandardFramework::new()
.configure(|c| c
@@ -79,6 +78,8 @@ async fn main() {
if let Err(why) = client.start().await {
println!("An error occurred while running the client: {:?} \n Check that there is a bot token set in config", why);
}
std::process::exit(0);
}
@@ -100,7 +101,7 @@ async fn pong(ctx: &Context, msg: &Message) -> CommandResult {
}
#[command]
#[aliases("c", "cons")]
#[aliases("c", "cons", "cmd")]
#[description("Send a command to the mindustry server console")]
#[example("status")]
#[min_args(1)]
@@ -108,7 +109,6 @@ async fn pong(ctx: &Context, msg: &Message) -> CommandResult {
async fn console(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let data = ctx.data.read().await;
let sock = data.get::<TcpSock>().unwrap();
let conf = data.get::<Config>().unwrap();
@@ -140,16 +140,34 @@ async fn console(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult
}
}
match cons_rw(sock, args.message()) {
Ok(n) => {
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Console")
.description(n)
.color(Color::ROSEWATER)
)
}).await?;
return Ok(());
}
Err(_e) => {
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Error")
.description("Unable to connect to the mindustry server\nCheck if server has restarted\nAttempting Reconnect")
.color(Color::RED)
)
}).await?;
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Console")
.description(cons_rw(sock, args.message()))
.color(Color::ROSEWATER)
)
}).await?;
drop(data);
recon(ctx, msg).await;
// exit(1);
}
}
Ok(())
}
@@ -164,14 +182,34 @@ async fn auth(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
let sock = data.get::<TcpSock>().unwrap();
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Console")
.description(cons_rw(sock, &format!("auth add {}", args.message())))
.color(Color::ROSEWATER)
)
}).await?;
match cons_rw(sock, &format!("auth add {}", args.message())) {
Ok(n) => {
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Console")
.description(n)
.color(Color::ROSEWATER)
)
}).await?;
return Ok(());
}
Err(_e) => {
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Error")
.description("Unable to connect to the mindustry server\nCheck if server has restarted\nAttempting Reconnect")
.color(Color::RED)
)
}).await?;
drop(data);
recon(ctx, msg).await;
// exit(1);
}
}
Ok(())
}

View File

@@ -1,34 +1,71 @@
use crate::structs::*;
use std::process::exit;
use std::str::FromStr;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write, Seek, BufRead};
use serenity::model::prelude::{Message, RoleId};
use serenity::prelude::{Context};
use serenity::utils::Color;
use std::{str};
use serenity::prelude::SerenityError;
use indoc::indoc;
pub fn cons_rw(sock: &TcpSock, input: &str) -> String {
pub fn cons_rw(sock: &TcpSock, input: &str) -> std::io::Result<String> {
match sock.stream.peer_addr() {
Ok(peer_addr) => {
println!("connection to {} is availible", peer_addr);
},
Err(e) => {
println!("Error: {:?}", e);
}
}
let mut output = String::new();
println!("creating writer");
let mut writer = std::io::BufWriter::new(sock.stream.try_clone().unwrap());
println!("creating reader");
let mut reader = std::io::BufReader::new(sock.stream.try_clone().unwrap());
loop {
match reader.read_line(&mut output) {
Ok(t) => t,
Err(_) => break(),
};
let mut buf = [0; 1024];
match sock.stream.peek(&mut buf) {
Ok(n) if n > 0 => {
println!("data to be cleared from queue \nclearing");
loop {
match reader.read_line(&mut output) {
Ok(t) => t,
Err(_) => break(),
};
}
}
Ok(_) => {
println!("connection to socket lost\nis the server stopped or restarted?");
return Err(std::io::Error::new(std::io::ErrorKind::Other, "unable to connect to server"))
}
Err(_e) => {
println!("queue empty");
}
}
// println!("clearing output variable");
output.clear();
writer.write((input.to_owned() + "\n").as_bytes()).unwrap();
// println!("writing");
writer.write((input.to_owned() + "\n").as_bytes()).expect("could not write to cons");
// println!("flushing writer");
writer.flush().expect("flush failed");
let mut _line = 0;
loop {
_line += 1;
// println!("reading line number {}", line);
match reader.read_line(&mut output) {
Ok(t) => t,
Err(_) => break(),
@@ -40,7 +77,7 @@ pub fn cons_rw(sock: &TcpSock, input: &str) -> String {
output
Ok(output)
}
@@ -156,3 +193,40 @@ pub fn is_command(command: String, command_vec: &Vec<String>) -> bool {
}
false
}
pub async fn recon(ctx: &Context, msg: &Message) {
let data = ctx.data.read().await;
let conf = data.get::<Config>().unwrap();
match TcpSock::new(conf.discord_settings.ip.clone(), conf.discord_settings.port.clone()) {
Ok(n) => {
drop(data);
let mut w_data = ctx.data.try_write().expect("unable to create write");
w_data.insert::<TcpSock>(n);
println!("reconnected");
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Success")
.description("Reconnection Succeeded\nRetry your command :)")
.color(Color::ROSEWATER)
)
}).await.unwrap();
}
Err(_e) => {
msg.channel_id.send_message(ctx, |m| {
m.content("")
.embed(|e| e
.title("Error")
.description("Reconnection unsuccessful\nStopping bot")
.color(Color::RED)
)
}).await.unwrap();
println!("unable to reconnect");
exit(1);
}
}
}

View File

@@ -1,4 +1,4 @@
use std::time::Duration;
use std::{time::Duration};
use std::net::TcpStream;
use serenity::prelude::{TypeMapKey};
use std::{str};
@@ -8,9 +8,13 @@ pub struct TcpSock {
}
impl TcpSock {
pub fn new(ip: String, port: String) -> std::io::Result<Self> {
let stream = TcpStream::connect(format!("{}:{}", ip, port)).expect("Tcp connection fail");
stream.set_read_timeout(Some(Duration::from_millis(25)))?;
pub fn new(ip: String, port: String) -> Result<Self, std::io::Error> {
let stream = match TcpStream::connect(format!("{}:{}", ip, port)) {
Ok(stream) => stream,
Err(e) => return Err(e),
};
stream.set_read_timeout(Some(Duration::from_millis(200)))?;
println!("Socket Connected!!");
Ok(TcpSock { stream })
}

Binary file not shown.