C#:
using Newtonsoft.Json;
using Oxide.Ext.Discord;
using Oxide.Ext.Discord.Attributes;
using Oxide.Ext.Discord.Builders.MessageComponents;
using Oxide.Ext.Discord.Entities;
using Oxide.Ext.Discord.Entities.Channels;
using Oxide.Ext.Discord.Entities.Gatway.Events;
using Oxide.Ext.Discord.Entities.Gatway;
using Oxide.Ext.Discord.Entities.Guilds;
using Oxide.Ext.Discord.Entities.Interactions.MessageComponents;
using Oxide.Ext.Discord.Entities.Interactions;
using Oxide.Ext.Discord.Entities.Messages;
using Oxide.Ext.Discord.Entities.Messages.Embeds;
using Oxide.Ext.Discord.Entities.Permissions;
using Oxide.Ext.Discord.Entities.Users;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Plugins
{
[Info("Discord Bot", "https://discord.gg/jb5puPzmnY", "0.0.1")]
[Description("")]
class DiscordBot : RustPlugin
{
private class Configuration
{
[JsonProperty("Token (https://discordapp.com/developers/applications)")]
public string token;
[JsonProperty("Channel ID, where the player will take the code to confirm the profile")]
public string channel;
[JsonProperty("Info text - line color on the left (https://gist.github.com/thomasbnt/b6f455e2c7d743b796917fa3c205f812#file-code_colors_discordjs-md)")]
public uint channelcolor;
[JsonProperty("Info text")]
public string channeltext;
[JsonProperty("Text on button")]
public string channelbutton;
[JsonProperty("Reply after button click")]
public string channelex;
[JsonProperty("Don't touch this field")]
public string channelmessageid;
public static Configuration Generate()
{
return new Configuration
{
token = "",
channel = "",
channelbutton = "Get code \n|||| \n�������� ���",
channelex = "\nYour code: {code} \n|||| \n��� ���: {code}",
channelmessageid = "",
channeltext = "",
channelcolor = 15277667
};
}
}
private static Configuration Settings;
protected override void LoadConfig()
{
base.LoadConfig();
try
{
Settings = Config.ReadObject<Configuration>();
}
catch
{
PrintWarning($"Error reading config, creating one new config!");
LoadDefaultConfig();
}
SaveConfig();
}
protected override void LoadDefaultConfig() => Settings = Configuration.Generate();
protected override void SaveConfig() => Config.WriteObject(Settings);
void OnServerInitialized()
{
foreach (var player in BasePlayer.activePlayerList)
{
OnPLayerConnection(player);
}
}
void Unload()
{
if (Client != null) Client.Disconnect();
}
void OnPLayerConnection(BasePlayer player)
{
}
private string RANDOMNUM() => UnityEngine.Random.Range(1000, 99999).ToString();
private Dictionary<ulong, string> DISCORDCODES = new Dictionary<ulong, string>();
private readonly DiscordSettings _discordSettings = new DiscordSettings();
private DiscordGuild _guild;
[DiscordClient] DiscordClient Client;
private void CreateClient()
{
_discordSettings.ApiToken = Settings.token;
_discordSettings.Intents = GatewayIntents.GuildMessages | GatewayIntents.DirectMessages | GatewayIntents.Guilds | GatewayIntents.GuildMembers;
_discordSettings.LogLevel = Ext.Discord.Logging.DiscordLogLevel.Error;
Client.Connect(_discordSettings);
timer.Once(5f, () =>
{
if (Client == null)
{
CreateClient();
Debug.Print("Discord reconnecting in 5 sec...");
}
else
{
DiscordChannel channel;
if (!_guild.Channels.TryGetValue(new Snowflake(Settings.channel), out channel))
{
Debug.Print("CHANNEL NOT FOUND! ({_guild.Channels.Count}).\n����� �� ����������! ({_guild.Channels.Count})");
return;
}
var embeds = new List<DiscordEmbed> { new DiscordEmbed { Color = new DiscordColor(Settings.channelcolor), Description = Settings.channeltext } };
var components = CreateComponents(Settings.channelbutton);
if (!string.IsNullOrEmpty(Settings.channelmessageid))
{
channel.GetChannelMessage(Client, new Snowflake(Settings.channelmessageid), message =>
{
message.Embeds = embeds;
message.Components.Clear();
message.Components = components;
message.EditMessage(Client);
},
error =>
{
if (error.HttpStatusCode == 404)
{
Debug.Print("all ok");
channel?.CreateMessage(Client, new MessageCreate { Embeds = embeds, Components = components }, message =>
{
Settings.channelmessageid = message.Id;
SaveConfig();
});
}
});
}
else
{
channel?.CreateMessage(Client, new MessageCreate { Embeds = embeds, Components = components },
message =>
{
Settings.channelmessageid = message.Id;
SaveConfig();
});
}
}
});
}
private void OnDiscordInteractionCreated(DiscordInteraction interaction)
{
if (interaction.Type != InteractionType.MessageComponent)
{
return;
}
if (!interaction.Data.ComponentType.HasValue || interaction.Data.ComponentType.Value != MessageComponentType.Button || interaction.Data.CustomId != $"{Name}_{ConVar.Server.ip}_{ConVar.Server.port}")
{
return;
}
DiscordUser user = interaction.User ?? interaction.Member?.User;
HandleAcceptLinkButton(interaction, user);
}
private void HandleAcceptLinkButton(DiscordInteraction interaction, DiscordUser user)
{
string num;
if (!DISCORDCODES.TryGetValue(user.Id.Id, out num))
{
num = DISCORDCODES[user.Id.Id] = RANDOMNUM();
}
string linkMessage = Formatter.ToPlaintext(Settings.channelex.Replace("{code}", num));
interaction.CreateInteractionResponse(Client, new InteractionResponse
{
Type = InteractionResponseType.ChannelMessageWithSource,
Data = new InteractionCallbackData
{
Content = linkMessage,
Flags = MessageFlags.Ephemeral
}
});
}
private void OnDiscordGatewayReady(GatewayReadyEvent ready)
{
_guild = ready.Guilds.FirstOrDefault().Value;
Debug.Print($"DISCORD BOT CONNECTED TO ID{_guild.Id}.\nDISCORD ��� ����������� �� ������� ID{_guild.Id}.");
}
private void CloseClient()
{
if (Client != null) Client.Disconnect();
}
private void CREATECHANNEL(string dsid, string text)
{
Snowflake ss = new Snowflake(dsid);
if (!_guild.Members.Any(x => x.Value.User.Id == ss)) return;
_guild.Members.First(x => x.Value.User.Id == ss).Value.User.SendDirectMessage(Client, new MessageCreate { Content = text });
}
private void SENDMESSAGE(string dsid, string text)
{
DiscordChannel channel = _guild.GetChannel(dsid);
if (channel != null)
{
channel?.CreateMessage(Client, text);
}
else
{
CREATECHANNEL(dsid, text);
}
}
public List<ActionRowComponent> CreateComponents(string button)
{
MessageComponentBuilder builder = new MessageComponentBuilder();
builder.AddActionButton(ButtonStyle.Success, button, $"{Name}_{ConVar.Server.ip}_{ConVar.Server.port}", false);
return builder.Build();
}
private readonly List<Regex> _regexTags = new List<Regex>
{
new Regex("<color=.+?>", RegexOptions.Compiled),
new Regex("<size=.+?>", RegexOptions.Compiled)
};
private readonly List<string> _tags = new List<string>
{
"</color>",
"`",
"</size>",
"<i>",
"</i>",
"<b>",
"</b>"
};
private string STRIP(string original)
{
if (string.IsNullOrEmpty(original))
{
return string.Empty;
}
foreach (string tag in _tags)
{
original = original.Replace(tag, "");
}
foreach (Regex regexTag in _regexTags)
{
original = regexTag.Replace(original, "");
}
return original;
}
private DiscordChannel GetChannel(string id)
{
return _guild.Channels.FirstOrDefault(x => x.Key.ToString() == id).Value;
}
}
}