1
0

Compare commits

...

2 Commits

Author SHA1 Message Date
7b9342e6e1 rework ReminderModule 2023-07-25 19:06:46 +08:00
16723fee4d refactoring 2023-07-25 19:04:53 +08:00
10 changed files with 256 additions and 249 deletions

View File

@ -36,7 +36,6 @@ namespace Discord_Bot
return;
var context = new SocketCommandContext(_client, message);
int argPos = 0;
JObject config = Functions.GetConfig();

View File

@ -61,6 +61,18 @@ namespace Discord_Bot
return (JObject)JsonConvert.DeserializeObject(configJson.ReadToEnd());
}
public static JToken GetConfigItem(string item)
{
var config = Functions.GetConfig();
if (config.TryGetValue(item, out var result))
{
return result;
}
var res = new JValue(0);
return res.Type == JTokenType.Null;
}
public static void SaveConfig(JObject config)
{
using (StreamWriter file = File.CreateText(Directory.GetCurrentDirectory() + @"/Config.json"))

View File

@ -0,0 +1,179 @@
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
using Discord;
namespace Discord_Bot
{
public class ExampleModule : ModuleBase<SocketCommandContext>
{
// .say hello world -> hello world
[Command("say")]
[Summary("Echoes a message.")]
public async Task SayAsync([Remainder] [Summary("The text to echo")] string echo)
{
RemoveLastUserMessage();
await ReplyAsync(echo);
}
private async void RemoveLastUserMessage()
{
var channel = Context.Channel as SocketTextChannel;
var items = await channel.GetMessagesAsync(1).FlattenAsync();
await channel.DeleteMessagesAsync(items);
}
[Command("hello")] // Command name.
[Summary("Say hello to the bot.")] // Command summary.
public async Task Hello()
=> await ReplyAsync($"Hello there, **{Context.User.Username}**!");
[Command("pick")]
[Alias("choose")] // Aliases that will also trigger the command.
[Summary("Pick something.")]
public async Task Pick([Remainder]string message = "")
{
string[] options = message.Split(new string[] { " or " }, StringSplitOptions.RemoveEmptyEntries);
string selection = options[new Random().Next(options.Length)];
// ReplyAsync() is a shortcut for Context.Channel.SendMessageAsync()
await ReplyAsync($"I choose **{selection}**");
}
[Command("cookie")]
[Summary("Give someone a cookie.")]
public async Task Cookie(SocketGuildUser user)
{
if (Context.Message.Author.Id == user.Id)
await ReplyAsync($"{Context.User.Mention} doesn't have anyone to share a cookie with... :(");
else
await ReplyAsync($"{Context.User.Mention} shared a cookie with **{user.Username}** :cookie:");
}
[Command("amiadmin")]
[Summary("Check your administrator status")]
public async Task AmIAdmin()
{
if ((Context.User as SocketGuildUser).GuildPermissions.Administrator)
await ReplyAsync($"Yes, **{Context.User.Username}**, you're an admin!");
else
await ReplyAsync($"No, **{Context.User.Username}**, you're **not** an admin!");
}
[Command("kick")]
[Summary("Kick a user from the server.")]
[RequireBotPermission(GuildPermission.KickMembers)]
[RequireUserPermission(GuildPermission.KickMembers)]
public async Task Kick(SocketGuildUser targetUser, [Remainder]string reason = "No reason provided.")
{
await targetUser.KickAsync(reason);
await ReplyAsync($"**{targetUser}** has been kicked. Bye bye :wave:");
}
[Command("ban")]
[Summary("Ban a user from the server")]
[RequireUserPermission(GuildPermission.BanMembers)]
[RequireBotPermission(GuildPermission.BanMembers)]
public async Task Ban(SocketGuildUser targetUser, [Remainder]string reason = "No reason provided.")
{
await Context.Guild.AddBanAsync(targetUser.Id, 0, reason);
await ReplyAsync($"**{targetUser}** has been banned. Bye bye :wave:");
}
[Command("unban")]
[Summary("Unban a user from the server")]
[RequireBotPermission(GuildPermission.BanMembers)]
[RequireUserPermission(GuildPermission.BanMembers)]
public async Task Unban(ulong targetUser)
{
await Context.Guild.RemoveBanAsync(targetUser);
await Context.Channel.SendMessageAsync($"The user has been unbanned :clap:");
}
[Command("purge")]
[Summary("Bulk deletes messages in chat")]
[RequireBotPermission(GuildPermission.ManageMessages)]
[RequireUserPermission(GuildPermission.ManageMessages)]
public async Task Purge(int delNumber)
{
var channel = Context.Channel as SocketTextChannel;
var items = await channel.GetMessagesAsync(delNumber + 1).FlattenAsync();
await channel.DeleteMessagesAsync(items);
}
[Command("reloadconfig")]
[Summary("Reloads the config and applies changes")]
[RequireOwner] // Require the bot owner to execute the command successfully.
public async Task ReloadConfig()
{
await Functions.SetBotStatusAsync(Context.Client);
await ReplyAsync("Reloaded!");
}
[Command("ping")]
[Summary("Show current latency.")]
public async Task Ping()
=> await ReplyAsync($"Latency: {Context.Client.Latency} ms");
[Command("avatar")]
[Alias("getavatar")]
[Summary("Get a user's avatar.")]
public async Task GetAvatar([Remainder]SocketGuildUser user = null)
=> await ReplyAsync($":frame_photo: **{(user ?? Context.User as SocketGuildUser).Username}**'s avatar\n{Functions.GetAvatarUrl(user)}");
[Command("info")]
[Alias("server", "serverinfo")]
[Summary("Show server information.")]
[RequireBotPermission(GuildPermission.EmbedLinks)] // Require the bot the have the 'Embed Links' permissions to execute this command.
public async Task ServerEmbed()
{
double botPercentage = Math.Round(Context.Guild.Users.Count(x => x.IsBot) / Context.Guild.MemberCount * 100d, 2);
EmbedBuilder embed = new EmbedBuilder()
.WithColor(0, 225, 225)
.WithDescription(
$"🏷️\n**Guild name:** {Context.Guild.Name}\n" +
$"**Guild ID:** {Context.Guild.Id}\n" +
$"**Created at:** {Context.Guild.CreatedAt:dd/M/yyyy}\n" +
$"**Owner:** {Context.Guild.Owner}\n\n" +
$"💬\n" +
$"**Users:** {Context.Guild.MemberCount - Context.Guild.Users.Count(x => x.IsBot)}\n" +
$"**Bots:** {Context.Guild.Users.Count(x => x.IsBot)} [ {botPercentage}% ]\n" +
$"**Channels:** {Context.Guild.Channels.Count}\n" +
$"**Roles:** {Context.Guild.Roles.Count}\n" +
$"**Emotes: ** {Context.Guild.Emotes.Count}\n\n" +
$"🌎 **Region:** {Context.Guild.VoiceRegionId}\n\n" +
$"🔒 **Security level:** {Context.Guild.VerificationLevel}")
.WithImageUrl(Context.Guild.IconUrl);
await ReplyAsync($":information_source: Server info for **{Context.Guild.Name}**", embed: embed.Build());
}
[Command("role")]
[Alias("roleinfo")]
[Summary("Show information about a role.")]
public async Task RoleInfo([Remainder]SocketRole role)
{
// Just in case someone tries to be funny.
if (role.Id == Context.Guild.EveryoneRole.Id)
return;
await ReplyAsync(
$":flower_playing_cards: **{role.Name}** information```ini" +
$"\n[Members] {role.Members.Count()}" +
$"\n[Role ID] {role.Id}" +
$"\n[Hoisted status] {role.IsHoisted}" +
$"\n[Created at] {role.CreatedAt:dd/M/yyyy}" +
$"\n[Hierarchy position] {role.Position}" +
$"\n[Color Hex] {role.Color}```");
}
// Please don't remove this command. I will appreciate it a lot <3
[Command("source")]
[Alias("sourcecode", "src")]
[Summary("Link the source code used for this bot.")]
public async Task Source()
=> await ReplyAsync($":heart: **{Context.Client.CurrentUser}** is based on this source code:\nhttps://github.com/VACEfron/Discord-Bot-Csharp");
}
}

View File

@ -1,48 +0,0 @@
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
namespace Discord_Bot
{
public class FunSample : ModuleBase<SocketCommandContext>
{
[Command("hello")] // Command name.
[Summary("Say hello to the bot.")] // Command summary.
public async Task Hello()
=> await ReplyAsync($"Hello there, **{Context.User.Username}**!");
[Command("pick")]
[Alias("choose")] // Aliases that will also trigger the command.
[Summary("Pick something.")]
public async Task Pick([Remainder]string message = "")
{
string[] options = message.Split(new string[] { " or " }, StringSplitOptions.RemoveEmptyEntries);
string selection = options[new Random().Next(options.Length)];
// ReplyAsync() is a shortcut for Context.Channel.SendMessageAsync()
await ReplyAsync($"I choose **{selection}**");
}
[Command("cookie")]
[Summary("Give someone a cookie.")]
public async Task Cookie(SocketGuildUser user)
{
if (Context.Message.Author.Id == user.Id)
await ReplyAsync($"{Context.User.Mention} doesn't have anyone to share a cookie with... :(");
else
await ReplyAsync($"{Context.User.Mention} shared a cookie with **{user.Username}** :cookie:");
}
[Command("amiadmin")]
[Summary("Check your administrator status")]
public async Task AmIAdmin()
{
if ((Context.User as SocketGuildUser).GuildPermissions.Administrator)
await ReplyAsync($"Yes, **{Context.User.Username}**, you're an admin!");
else
await ReplyAsync($"No, **{Context.User.Username}**, you're **not** an admin!");
}
}
}

View File

@ -1,14 +0,0 @@
using Discord.Commands;
namespace Budet_cho_bot.Modules;
public class InfoModule : ModuleBase<SocketCommandContext>
{
// ~say hello world -> hello world
[Command("say")]
[Summary("Echoes a message.")]
public Task SayAsync([Remainder] [Summary("The text to echo")] string echo)
=> ReplyAsync(echo);
// ReplyAsync is a method on ModuleBase
}

View File

@ -1,60 +0,0 @@
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace Discord_Bot
{
public class ModSample : ModuleBase<SocketCommandContext>
{
[Command("kick")]
[Summary("Kick a user from the server.")]
[RequireBotPermission(GuildPermission.KickMembers)]
[RequireUserPermission(GuildPermission.KickMembers)]
public async Task Kick(SocketGuildUser targetUser, [Remainder]string reason = "No reason provided.")
{
await targetUser.KickAsync(reason);
await ReplyAsync($"**{targetUser}** has been kicked. Bye bye :wave:");
}
[Command("ban")]
[Summary("Ban a user from the server")]
[RequireUserPermission(GuildPermission.BanMembers)]
[RequireBotPermission(GuildPermission.BanMembers)]
public async Task Ban(SocketGuildUser targetUser, [Remainder]string reason = "No reason provided.")
{
await Context.Guild.AddBanAsync(targetUser.Id, 0, reason);
await ReplyAsync($"**{targetUser}** has been banned. Bye bye :wave:");
}
[Command("unban")]
[Summary("Unban a user from the server")]
[RequireBotPermission(GuildPermission.BanMembers)]
[RequireUserPermission(GuildPermission.BanMembers)]
public async Task Unban(ulong targetUser)
{
await Context.Guild.RemoveBanAsync(targetUser);
await Context.Channel.SendMessageAsync($"The user has been unbanned :clap:");
}
[Command("purge")]
[Summary("Bulk deletes messages in chat")]
[RequireBotPermission(GuildPermission.ManageMessages)]
[RequireUserPermission(GuildPermission.ManageMessages)]
public async Task Purge(int delNumber)
{
var channel = Context.Channel as SocketTextChannel;
var items = await channel.GetMessagesAsync(delNumber + 1).FlattenAsync();
await channel.DeleteMessagesAsync(items);
}
[Command("reloadconfig")]
[Summary("Reloads the config and applies changes")]
[RequireOwner] // Require the bot owner to execute the command successfully.
public async Task ReloadConfig()
{
await Functions.SetBotStatusAsync(Context.Client);
await ReplyAsync("Reloaded!");
}
}
}

View File

@ -1,71 +1,70 @@
using Discord.Commands;
using Discord.Commands.Builders;
using Newtonsoft.Json.Linq;
namespace Discord_Bot
{
public class ReminderModule : ModuleBase<SocketCommandContext>
{
private long dayPeriod = 24 * 60 * 60 * 1000;
private const long DAY_PERIOD = 24 * 60 * 60 * 1000; // 10 * 1000; //
private Timer reminderTimer;
[Command("remindertime")]
public async Task ReminderTime([Remainder]string message = "")
protected override void OnModuleBuilding(CommandService commandService, ModuleBuilder builder)
{
SaveToConfig("reminderTime", message);
var time = message.Split(":");
SetReminderTime(int.Parse(time[0]), int.Parse(time[1]));
base.OnModuleBuilding(commandService, builder);
Console.WriteLine($"{DateTime.Now.TimeOfDay:hh\\:mm\\:ss} | hello world ");
ReloadTimers();
}
[Command("remindertime")]
private async Task SetReminderTime([Remainder]string message = "")
{
SaveToConfig("reminderTime", Utility.ParseMessage(message));
ReloadTimers();
await ReplyAsync($"Заебись");
}
[Command("calltime")]
public async Task CallTime([Remainder]string message = "")
[Command("sequence")]
private async Task SetSequence([Remainder]string message = "")
{
SaveToConfig("callTime", message);
var time = message.Split(":");
SetReminderTime(int.Parse(time[0]), int.Parse(time[1]));
SaveToConfig("sequence", message);
await ReplyAsync($"Заебись");
}
[Command("users")]
public async Task Users([Remainder]string message = "")
private async Task Users([Remainder]string message = "")
{
SaveToConfig("users", message);
var time = message.Split(":");
SetReminderTime(int.Parse(time[0]), int.Parse(time[1]));
await ReplyAsync($"Заебись");
}
public void SetReminderTime(int hours, int minutes)
private void ReloadTimers()
{
var time = Functions.GetConfigItem("reminderTime");
if (time.Type == JTokenType.Boolean)
return;
var nextReminder = Utility.ParseTime(time.ToString());
var now = DateTime.Now;
var nextReminder = new DateTime(now.Year, now.Month, now.Day, hours, minutes, 0);
var span = (nextReminder - now).TotalMilliseconds;
reminderTimer = new Timer(SendReminder, "sd", (long)span, dayPeriod);
ReloadTimers();
}
public void SetCallTime(int hours, int minutes)
{
var now = DateTime.Now;
var nextReminder = new DateTime(now.Year, now.Month, now.Day, hours, minutes, 0);
var span = (nextReminder - now).TotalMilliseconds;
reminderTimer = new Timer(SendReminder, "sd", (long)span, dayPeriod);
ReloadTimers();
if (span < 0)
{
// skip to next day
nextReminder = nextReminder.AddDays(1);
span = (nextReminder - now).TotalMilliseconds;
}
reminderTimer = new Timer(SendReminder, "sd", (long)span, DAY_PERIOD);
}
private async void SendReminder(object? state)
{
var users = Functions.GetConfig()["users"].ToString();
//check sequence
var users = Functions.GetConfigItem("users").ToString();
await ReplyAsync($"{users}\nБудет чо?");
}
private async void SendCall(object? state)
{
await ReplyAsync($"?");
}
private void SaveToConfig(string key, string data)
{
@ -73,10 +72,5 @@ namespace Discord_Bot
config[key] = data;
Functions.SaveConfig(config);
}
private void ReloadTimers()
{
}
}
}

View File

@ -1,79 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Globalization;
namespace Discord_Bot
{
public class UtilitySample : ModuleBase<SocketCommandContext>
{
[Command("ping")]
[Summary("Show current latency.")]
public async Task Ping()
=> await ReplyAsync($"Latency: {Context.Client.Latency} ms");
[Command("avatar")]
[Alias("getavatar")]
[Summary("Get a user's avatar.")]
public async Task GetAvatar([Remainder]SocketGuildUser user = null)
=> await ReplyAsync($":frame_photo: **{(user ?? Context.User as SocketGuildUser).Username}**'s avatar\n{Functions.GetAvatarUrl(user)}");
[Command("info")]
[Alias("server", "serverinfo")]
[Summary("Show server information.")]
[RequireBotPermission(GuildPermission.EmbedLinks)] // Require the bot the have the 'Embed Links' permissions to execute this command.
public async Task ServerEmbed()
{
double botPercentage = Math.Round(Context.Guild.Users.Count(x => x.IsBot) / Context.Guild.MemberCount * 100d, 2);
EmbedBuilder embed = new EmbedBuilder()
.WithColor(0, 225, 225)
.WithDescription(
$"🏷️\n**Guild name:** {Context.Guild.Name}\n" +
$"**Guild ID:** {Context.Guild.Id}\n" +
$"**Created at:** {Context.Guild.CreatedAt:dd/M/yyyy}\n" +
$"**Owner:** {Context.Guild.Owner}\n\n" +
$"💬\n" +
$"**Users:** {Context.Guild.MemberCount - Context.Guild.Users.Count(x => x.IsBot)}\n" +
$"**Bots:** {Context.Guild.Users.Count(x => x.IsBot)} [ {botPercentage}% ]\n" +
$"**Channels:** {Context.Guild.Channels.Count}\n" +
$"**Roles:** {Context.Guild.Roles.Count}\n" +
$"**Emotes: ** {Context.Guild.Emotes.Count}\n\n" +
$"🌎 **Region:** {Context.Guild.VoiceRegionId}\n\n" +
$"🔒 **Security level:** {Context.Guild.VerificationLevel}")
.WithImageUrl(Context.Guild.IconUrl);
await ReplyAsync($":information_source: Server info for **{Context.Guild.Name}**", embed: embed.Build());
}
[Command("role")]
[Alias("roleinfo")]
[Summary("Show information about a role.")]
public async Task RoleInfo([Remainder]SocketRole role)
{
// Just in case someone tries to be funny.
if (role.Id == Context.Guild.EveryoneRole.Id)
return;
await ReplyAsync(
$":flower_playing_cards: **{role.Name}** information```ini" +
$"\n[Members] {role.Members.Count()}" +
$"\n[Role ID] {role.Id}" +
$"\n[Hoisted status] {role.IsHoisted}" +
$"\n[Created at] {role.CreatedAt:dd/M/yyyy}" +
$"\n[Hierarchy position] {role.Position}" +
$"\n[Color Hex] {role.Color}```");
}
// Please don't remove this command. I will appreciate it a lot <3
[Command("source")]
[Alias("sourcecode", "src")]
[Summary("Link the source code used for this bot.")]
public async Task Source()
=> await ReplyAsync($":heart: **{Context.Client.CurrentUser}** is based on this source code:\nhttps://github.com/VACEfron/Discord-Bot-Csharp");
}
}

25
Budet-cho-bot/Utility.cs Normal file
View File

@ -0,0 +1,25 @@
using Newtonsoft.Json.Linq;
namespace Discord_Bot;
public static class Utility
{
public static string ParseMessage(string message)
{
var time = message.Split(":");
if (time.Length != 2)
{
throw new ArgumentException("Время неправильное. Хуйня твоё время");
return null;
}
var now = DateTime.Now;
var date = new DateTime(now.Year, now.Month, now.Day, int.Parse(time[0]), int.Parse(time[1]), 0);
return Newtonsoft.Json.JsonConvert.SerializeObject(date);
}
public static DateTime ParseTime(string token)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(token);
}
}

View File

@ -2,9 +2,8 @@
"version": "1.0",
"token": "MTA4NDA5MTA4OTE1NTI4MDkxNw.G77VAz.3O8uS-D4nwp1Ax8iZMBIx0Z9gsYNNOwPFfGRl8",
"prefixes": ["."],
"join_message": "Hello, I'm Discord Bot! :heart:",
"currently": "playing|listening|watching|streaming",
"join_message": "Дратуте! :heart:",
"currently": "playing",
"playing_status": "майныч",
"status": "online|dnd|idle|offline",
"reminderTime": "1:12"
"status": "online"
}