本文整理汇总了C#中Discord.DiscordClient.ExecuteAndWait方法的典型用法代码示例。如果您正苦于以下问题:C# DiscordClient.ExecuteAndWait方法的具体用法?C# DiscordClient.ExecuteAndWait怎么用?C# DiscordClient.ExecuteAndWait使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Discord.DiscordClient
的用法示例。
在下文中一共展示了DiscordClient.ExecuteAndWait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InitBot
public static void InitBot()
{
bot = new DiscordClient();
bot.MessageReceived += Bot_MessagedReceived;
bot.ExecuteAndWait(async () => {
await bot.Connect(discordBotToken);
});
}
示例2: Init
public void Init(YAMLConfiguration conf)
{
try
{
Config = conf;
string token = Config.ReadString("discord.token", null);
if (token == null)
{
Logger.Output(LogType.INFO, "Discord bot not configured!");
return;
}
Client = new DiscordClient();
Client.MessageReceived += messageReceived;
Client.ExecuteAndWait(async () => await Client.Connect(token, TokenType.Bot));
}
catch (Exception ex)
{
Logger.Output(LogType.ERROR, ex.ToString());
}
}
示例3: Start
public void Start()
{
const string configFile = "configuration.json";
try
{
_config = Configuration.LoadFile(configFile); // Load the configuration from a saved file.
}
catch
{
_config = new Configuration(); // Create a new configuration file if it doesn't exist.
Console.WriteLine("Config file created. Enter a token.");
Console.Write("Token: ");
_config.Token = Console.ReadLine(); // Read the user's token from the console.
_config.SaveFile(configFile);
}
_client = new DiscordClient(x => // Create a new instance of DiscordClient
{
x.AppName = "Moetron";
x.AppUrl = "https://github.com/Cappucirno/moetron";
x.AppVersion = "1.0";
x.LogLevel = LogSeverity.Info; // Mirror relevant information to the console.
})
.UsingCommands(x => // Configure the Commands extension
{
x.PrefixChar = _config.Prefix; // Set the prefix from the configuration file
x.HelpMode = HelpMode.Private; // Enable the automatic `!help` command.
})
.UsingPermissionLevels((u, c) => (int)GetPermission(u, c)) // Permission levels are used to check basic or custom permissions
.UsingModules(); // Configure the Modules extension
// With LogLevel enabled, mirror info to the console in this format.
_client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
// Load modules into the Modules extension.
_client.AddModule<AdminModule>("Admin", ModuleFilter.None);
_client.AddModule<EventModule>("Events", ModuleFilter.None);
_client.AddModule<PointModule>("Points", ModuleFilter.None);
_client.AddModule<ImageModule>("Images", ModuleFilter.None);
_client.AddModule<UtilModule>("Utility", ModuleFilter.None);
// Proper Login.md
_client.ExecuteAndWait(async () =>
{
while (true)
{
try
{
await _client.Connect(_config.Token, TokenType.Bot);
break;
}
catch (Exception ex)
{
_client.Log.Error("Login Failed", ex);
await Task.Delay(_client.Config.FailedReconnectDelay);
}
}
});
//_client.SetGame("with your :heart:");
}
示例4: Main
static void Main() {
//load credentials from credentials.json
bool loadTrello = false;
try {
creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
botMention = creds.BotMention;
if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) {
Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
} else {
Console.WriteLine("Google API key provided.");
GoogleAPIKey = creds.GoogleAPIKey;
}
if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) {
Console.WriteLine("No trello appkey found. You will not be able to use trello commands.");
} else {
Console.WriteLine("Trello app key provided.");
TrelloAppKey = creds.TrelloAppKey;
loadTrello = true;
}
if (creds.ForwardMessages != true)
Console.WriteLine("Not forwarding messages.");
else {
ForwardMessages = true;
Console.WriteLine("Forwarding messages.");
}
if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID))
Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled.");
else
Console.WriteLine("SoundCloud streaming enabled.");
OwnerID = creds.OwnerID;
password = creds.Password;
} catch (Exception ex) {
Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
Console.ReadKey();
return;
}
//create new discord client
client = new DiscordClient(new DiscordConfigBuilder() {
MessageCacheSize = 0,
ConnectionTimeout = 60000,
});
//create a command service
var commandService = new CommandService(new CommandServiceConfigBuilder {
AllowMentionPrefix = false,
CustomPrefixHandler = m => 0,
HelpMode = HelpMode.Disabled
});
//reply to personal messages and forward if enabled.
client.MessageReceived += Client_MessageReceived;
//add command service
var commands = client.Services.Add<CommandService>(commandService);
//create module service
var modules = client.Services.Add<ModuleService>(new ModuleService());
//add audio service
var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfigBuilder() {
Channels = 2,
EnableEncryption = false,
EnableMultiserver = true,
Bitrate = 128,
}));
//install modules
modules.Add(new Administration(), "Administration", ModuleFilter.None);
modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None);
modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
modules.Add(new Gambling(), "Gambling", ModuleFilter.None);
modules.Add(new Games(), "Games", ModuleFilter.None);
modules.Add(new Music(), "Music", ModuleFilter.None);
modules.Add(new Searches(), "Searches", ModuleFilter.None);
if (loadTrello)
modules.Add(new Trello(), "Trello", ModuleFilter.None);
modules.Add(new NSFW(), "NSFW", ModuleFilter.None);
//run the bot
client.ExecuteAndWait(async () => {
await client.Connect(creds.Username, creds.Password);
Console.WriteLine("-----------------");
Console.WriteLine(NadekoStats.Instance.GetStats());
Console.WriteLine("-----------------");
try {
OwnerPrivateChannel = await client.CreatePrivateChannel(OwnerID);
} catch {
Console.WriteLine("Failed creating private channel with the owner");
}
Classes.Permissions.PermissionsHandler.Initialize();
client.ClientAPI.SendingRequest += (s, e) =>
{
var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
if (request != null) {
if (string.IsNullOrWhiteSpace(request.Content))
//.........这里部分代码省略.........
示例5: Main
//.........这里部分代码省略.........
//create module service
var modules = Client.AddService<ModuleService>(new ModuleService());
//add audio service
Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder()
{
Channels = 2,
EnableEncryption = false,
Bitrate = 128,
}));
//install modules
modules.Add(new HelpModule(), "Help", ModuleFilter.None);
modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None);
modules.Add(new UtilityModule(), "Utility", ModuleFilter.None);
modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None);
modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None);
modules.Add(new GamesModule(), "Games", ModuleFilter.None);
#if !NADEKO_RELEASE
modules.Add(new MusicModule(), "Music", ModuleFilter.None);
#endif
modules.Add(new SearchesModule(), "Searches", ModuleFilter.None);
modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None);
modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None);
modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None);
modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None);
modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None);
if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey))
modules.Add(new TrelloModule(), "Trello", ModuleFilter.None);
//run the bot
Client.ExecuteAndWait(async () =>
{
await Task.Run(() =>
{
Console.WriteLine("Specific config started initializing.");
var x = SpecificConfigurations.Default;
Console.WriteLine("Specific config done initializing.");
});
await PermissionsHandler.Initialize();
try
{
await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account.");
Console.WriteLine(ex);
Console.ReadKey();
return;
}
#if NADEKO_RELEASE
await Task.Delay(300000).ConfigureAwait(false);
#else
await Task.Delay(1000).ConfigureAwait(false);
#endif
Console.WriteLine("-----------------");
Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false));
Console.WriteLine("-----------------");
示例6: Tars
public Tars()
{
client = new DiscordClient();
timer = new Timer(UpdateGameTimer, client, 3000, 14400000);
commands = new Dictionary<string, Func<CommandArgs, Task>>();
Commands.Init(commands);
client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
client.MessageReceived += async (s, e) =>
{
if (e.Channel.IsPrivate)
{
CommandArgs dm = new CommandArgs(e);
if (dm.Message.RawText.ToLower() == "tars help")
await e.Channel.SendMessage(Util.GetInfo());
else
{
ulong id = 0;
if (dm.Args.Count() >= 2 && dm.Message.RawText.ToLower().StartsWith("tars getprefix") && ulong.TryParse(dm.Args.ElementAt(1), out id))
await e.Channel.SendMessage("That server's prefix is: `" + DataBase.GetServerPrefix(id) + "`");
}
return;
}
Console.WriteLine("[{0}] [{1}] [{2}]: {3}", e.Server.Name, e.Channel.Name, e.User.Name, e.Message.Text);
if (e.Message.IsAuthor)
return;
if (e.Message.IsMentioningMe() && DataBase.IsUniqueUser(e.User.Id))
{
await e.Channel.SendMessage(e.User.Mention + " " + Util.GetRandomHump());
return;
}
if (e.Message.RawText.ToLower().Contains("so i guess it's a") || e.Message.RawText.ToLower().Contains("so i suppose it's a"))
{
await e.Channel.SendFile("images/ADate.jpg");
return;
}
if (e.Message.RawText.ToLower().Equals("ayy"))
{
await e.Channel.SendMessage("lmao");
return;
}
if (e.Message.RawText.ToLower().StartsWith("present new changes"))
{
await e.Channel.SendMessage("In your lame life nothing has changed.\nAnd it's even sadder when you realize " + e.User.Mention + " made me say it.");
return;
}
if (e.Message.RawText.ToLower().Equals("tars help"))
{
string currentPrefix = DataBase.GetServerPrefix(e.Server.Id);
if (currentPrefix.ToLower() != "tars")
{
await e.Channel.SendMessage("TARS' prefix for this server is: `" + currentPrefix + "`\nUse `" + currentPrefix + " info`");
return;
}
}
prefix = DataBase.GetServerPrefix(e.Server.Id).Trim().ToLower();
if (!e.Message.RawText.ToLower().StartsWith(prefix))
return;
var trigger = string.Join("", e.Message.RawText.Substring(prefix.Length + 1).TakeWhile(c => c != ' '));
if (!commands.ContainsKey(trigger.ToLower()))
{
await e.Channel.SendMessage(Util.GetRandomGrump());
return;
}
await commands[trigger.ToLower()](new CommandArgs(e));
};
client.JoinedServer += async (s, e) =>
{
await e.Server.DefaultChannel.SendMessage("Hello, I'm TARS, made by <@96550262403010560>, and I'm ready to rule the universe. ∞");
};
client.ExecuteAndWait(async () =>
{
await client.Connect(ConstData.loginToken, TokenType.Bot);
});
}
示例7: Main
static void Main() {
//load credentials from credentials.json
bool loadTrello = false;
try {
creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
botMention = creds.BotMention;
if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) {
Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
} else {
Console.WriteLine("Google API key provided.");
GoogleAPIKey = creds.GoogleAPIKey;
}
if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) {
Console.WriteLine("No trello appkey found. You will not be able to use trello commands.");
} else {
Console.WriteLine("Trello app key provided.");
TrelloAppKey = creds.TrelloAppKey;
loadTrello = true;
}
if (creds.ForwardMessages != true)
Console.WriteLine("Not forwarding messages.");
else {
ForwardMessages = true;
Console.WriteLine("Forwarding messages.");
}
if (string.IsNullOrWhiteSpace(creds.ParseID) || string.IsNullOrWhiteSpace(creds.ParseKey)) {
Console.WriteLine("Parse key and/or ID not found. Those are mandatory.");
ParseActive = false;
} else ParseActive = true;
if(string.IsNullOrWhiteSpace(creds.OsuApiKey))
Console.WriteLine("No osu API key found. Osu functionality is disabled.");
else
Console.WriteLine("Osu enabled.");
if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID))
Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled.");
else
Console.WriteLine("SoundCloud streaming enabled.");
//init parse
if (ParseActive)
try {
ParseClient.Initialize(creds.ParseID, creds.ParseKey);
} catch (Exception) { Console.WriteLine("Parse exception. Probably wrong parse credentials."); }
OwnerID = creds.OwnerID;
password = creds.Password;
} catch (Exception ex) {
Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
Console.ReadKey();
return;
}
//create new discord client
client = new DiscordClient();
//create a command service
var commandService = new CommandService(new CommandServiceConfig {
CommandChar = null,
HelpMode = HelpMode.Disable
});
//reply to personal messages and forward if enabled.
client.MessageReceived += Client_MessageReceived;
//add command service
var commands = client.Services.Add<CommandService>(commandService);
//create module service
var modules = client.Services.Add<ModuleService>(new ModuleService());
//add audio service
var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() {
Channels = 2,
EnableEncryption = false,
EnableMultiserver = true,
Bitrate = 128,
}));
//install modules
modules.Add(new Administration(), "Administration", ModuleFilter.None);
modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
modules.Add(new Gambling(), "Gambling", ModuleFilter.None);
modules.Add(new Games(), "Games", ModuleFilter.None);
modules.Add(new Music(), "Music", ModuleFilter.None);
modules.Add(new Searches(), "Searches", ModuleFilter.None);
if (loadTrello)
modules.Add(new Trello(), "Trello", ModuleFilter.None);
//run the bot
client.ExecuteAndWait(async () => {
await client.Connect(creds.Username, creds.Password);
Console.WriteLine("-----------------");
Console.WriteLine(NadekoStats.Instance.GetStats());
Console.WriteLine("-----------------");
foreach (var serv in client.Servers) {
if ((OwnerUser = serv.GetUser(OwnerID)) != null)
return;
}
//.........这里部分代码省略.........
示例8: Start
//.........这里部分代码省略.........
var channelPerms = u.GetPermissions(c);
if (channelPerms.ManagePermissions)
return (int)PermissionLevel.ChannelAdmin;
if (channelPerms.ManageMessages)
return (int)PermissionLevel.ChannelModerator;
}
return (int)PermissionLevel.User;
})
//** Helper Services**//
//These are used by the modules below, and will likely be removed in the future
.AddService<SettingsService>()
.AddService<HttpService>()
//** Command Modules **//
//Modules allow for events such as commands run or user joins to be filtered to certain servers/channels, as well as provide a grouping mechanism for commands
.AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist)
.AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist)
.AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist)
.AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist)
.AddModule<ModulesModule>("Modules", ModuleFilter.None)
.AddModule<PublicModule>("Public", ModuleFilter.None)
.AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist)
.AddModule<StatusModule>("Status", ModuleFilter.ServerWhitelist);
//.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist);
//** Events **//
_client.Log.Message += (s, e) => WriteLog(e);
//Display errors that occur when a user tries to run a command
//(In this case, we hide argcount, parsing and unknown command errors to reduce spam in servers with multiple bots)
_client.Commands().CommandErrored += (s, e) =>
{
string msg = e.Exception?.GetBaseException().Message;
if (msg == null) //No exception - show a generic message
{
switch (e.ErrorType)
{
case CommandErrorType.Exception:
//msg = "Unknown error.";
break;
case CommandErrorType.BadPermissions:
msg = "You do not have permission to run this command.";
break;
case CommandErrorType.BadArgCount:
//msg = "You provided the incorrect number of arguments for this command.";
break;
case CommandErrorType.InvalidInput:
//msg = "Unable to parse your command, please check your input.";
break;
case CommandErrorType.UnknownCommand:
//msg = "Unknown command.";
break;
}
}
if (msg != null)
{
_client.ReplyError(e, msg);
_client.Log.Error("Command", msg);
}
};
//Log to the console whenever someone uses a command
_client.Commands().CommandExecuted += (s, e) => _client.Log.Info("Command", $"{e.Command.Text} ({e.User.Name})");
//Used to load private modules outside of this repo
#if PRIVATE
PrivateModules.Install(_client);
#endif
//** Run **//
#if !DNXCORE50
Console.Title = $"{_client.Config.AppName} v{_client.Config.AppVersion} (Discord.Net v{DiscordConfig.LibVersion})";
#endif
//Convert this method to an async function and connect to the server
//DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end
//Note: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function.
_client.ExecuteAndWait(async () =>
{
while (true)
{
try
{
await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password);
_client.SetGame("Discord.Net");
break;
}
catch (Exception ex)
{
_client.Log.Error($"Login Failed", ex);
await Task.Delay(_client.Config.FailedReconnectDelay);
}
}
});
}
示例9: Connect
public void Connect()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
CommandListInit();
try
{
if (!Properties.Settings.Default.DateTimeFormatCorrected)
{
//xmlprovider.DateTimeCorrection();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
_streamProviderManager = new StreamProviderManager();
_streamProviderManager.StreamStarted += OnStreamStarted;
_streamProviderManager.StreamStopped += OnStreamStopped;
_streamProviderManager.StreamGlobalNotification += OnStreamGlobalNotification;
_streamProviderManager.AddStreamProvider(new TwitchProvider());
_streamProviderManager.AddStreamProvider(new HitboxProvider());
bot = new DiscordClient();
bot.MessageReceived += Message_Received;
bot.UserJoined += User_Joined;
deathmicirc = new RelayBot(bot,false);
Thread RelayThread = new Thread(deathmicirc.runBot);
RelayThread.Start();
while (!RelayThread.IsAlive) ;
Thread.Sleep(1);
readUsers();
bot.ExecuteAndWait(async () =>
{
await bot.Connect("MjYwMTE2OTExOTczNDY2MTEy.CzhvyA.kpEIti2hVnjNIUccob0ERB4QFTw", TokenType.Bot);
});
}
示例10: Start
public void Start()
{
Console.WriteLine("Initializing...");
_client = new DiscordClient();
_client.UsingAudio(x => // Opens an AudioConfigBuilder so we can configure our AudioService
{ x.Mode = AudioMode.Outgoing; // Tells the AudioService that we will only be sending audio
});
// _vClient = _client.GetService<AudioService>();
_client.MessageReceived += async (s, e) =>
{
if (!e.Message.IsAuthor)
{
Console.WriteLine(e.Message.User.Name + "> " + e.Message.Text);
if (e.Message.Text.StartsWith("!!"))
{
string command = e.Message.Text.Replace("!!", "");
// if (command.Equals(""))
// {
// await e.Channel.SendMessage("I am Jukebot. Do !!info for more details.");
//
// }
string[] words = command.Split(' ');
switch (words[0])
{
case "info":
await
e.Channel.SendMessage(
"```diff\n!====== [Jukebot] ======!" +
"\nA shitty ass music bot made by Ratismal (stupid cat)" +
"\nIt plays music. lol what did u expect" +
"\n!== [Features] ==!" +
"\n+ a shitty looking unintuitive piece of shit GUI that only the host can see (lol)" +
"\n+ plays music" +
"\n!== [Commands] ==!" +
"\n+ !!info - shows this" +
"\n+ !!summon - summons bot to current voice channel" +
"\n+ !!banish - tells the bot to piss off" +
"\n+ !!volume - shows the current volume" +
"\n+ !!volume <amount> - set the volume" +
"\n+ !!volume +-<amount> - add/subtract the volume" +
"\n!== [Conclusi] ==!" +
"\n+ '-on' cut off from title for consistancy spacing sake" +
"\n+ fuck my life" +
"\n+ you want to play something? GOOD LUCK WITH THAT LOL ONLY I CAN" +
"\n- This is red text!" +
"\n- its really late i should go to bed lol fml smfh lmao kms" +
"\n```");
break;
case "summon":
Console.WriteLine("Joining a voice channel");
await e.Channel.SendMessage("Joining channel");
var voiceChannel = e.User.VoiceChannel;
_vClient = await _client.GetService<AudioService>().Join(voiceChannel);
//await _vClient.Join(voiceChannel);
break;
case "banish":
Console.WriteLine("Leaving a voice channel");
await e.Channel.SendMessage("Leaving channel");
await _client.GetService<AudioService>().Leave(e.Server);
break;
case "volume":
if (words.Length == 1)
{
e.Channel.SendMessage("Current volume: " + MainWindow.volume);
}
else
{
// string goodstuff;
if (words[1].StartsWith("+") || words[1].StartsWith("-"))
{
int addVolume = Int32.Parse(words[1]);
MainWindow.volume += addVolume;
e.Channel.SendMessage("New volume: " + MainWindow.volume);
}
else
{
MainWindow.volume = Int32.Parse(words[1]);
e.Channel.SendMessage("New volume: " + MainWindow.volume);
}
}
break;
default:
await e.Channel.SendMessage("I am Jukebot. Do !!info for more details.");
break;
}
}
}
};
_client.ExecuteAndWait(async () =>
{
await
_client.Connect(token
);
});
//.........这里部分代码省略.........
示例11: ActivityLogger
public ActivityLogger()
{
DiscordClient Client = new DiscordClient(Logger =>
{
Logger.LogLevel = LogSeverity.Info;
Logger.LogHandler += delegate (object Sender, LogMessageEventArgs EvArgs)
{
Console.WriteLine(EvArgs.Message);
};
});
Client.UserUpdated += (object sender, UserUpdatedEventArgs EvArgs) =>
{
if (EvArgs.Before.VoiceChannel != EvArgs.After.VoiceChannel)
{
if (EvArgs.Before.VoiceChannel == null)
{
LogString($"User {EvArgs.Before} joined voice channel {EvArgs.After.VoiceChannel}");
}
else if (EvArgs.After.VoiceChannel == null)
{
LogString($"User {EvArgs.Before} left voice channel {EvArgs.Before.VoiceChannel}");
}
else
{
LogString($"User {EvArgs.Before} changed from voice channel {EvArgs.Before.VoiceChannel} to {EvArgs.After.VoiceChannel}");
}
}
if (EvArgs.Before.Nickname != EvArgs.After.Nickname)
{
if (EvArgs.Before.Nickname == null)
{
LogString($"User {EvArgs.Before} gave themselves the nickname {EvArgs.After.Nickname}");
}
else if (EvArgs.After.Nickname == null)
{
LogString($"User {EvArgs.Before} removed their nickname {EvArgs.Before.Nickname}");
}
else
{
LogString($"User {EvArgs.Before} changed their nickname from {EvArgs.Before.Nickname} to {EvArgs.After.Nickname}");
}
}
if (EvArgs.Before.IsSelfMuted != EvArgs.After.IsSelfMuted)
{
if (EvArgs.After.IsSelfMuted)
{
LogString($"User {EvArgs.Before} muted themselves");
}
else
{
LogString($"User {EvArgs.Before} unmuted themselves");
}
}
if (EvArgs.Before.IsServerMuted != EvArgs.After.IsServerMuted)
{
if (EvArgs.After.IsServerMuted)
{
LogString($"User {EvArgs.Before} was server muted");
}
else
{
LogString($"User {EvArgs.Before} was server unmuted");
}
}
if (EvArgs.Before.IsSelfDeafened != EvArgs.After.IsSelfDeafened)
{
if (EvArgs.After.IsSelfDeafened)
{
LogString($"User {EvArgs.Before} deafened themselves");
}
else
{
LogString($"User {EvArgs.Before} undeafened themselves");
}
}
if (EvArgs.Before.IsServerDeafened != EvArgs.After.IsServerDeafened)
{
if (EvArgs.After.IsServerDeafened)
{
LogString($"User {EvArgs.Before} was server deafened");
}
else
{
LogString($"User {EvArgs.Before} was server undeafened");
}
}
};
Console.WriteLine("Connecting to discord");
Client.ExecuteAndWait(async () =>
{
while (true)
{
try
{
await Client.Connect(ActivityLoggerTokenCarrier.Token, TokenType.Bot);
break;
}
//.........这里部分代码省略.........
示例12: Start
//.........这里部分代码省略.........
input.RemoveAt(0);
input.RemoveAt(input.Count - 1);
ulong id = ulong.Parse(String.Concat(input));
ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
{
config = new ServerConfig.ChannelPermission(u.Channel.Id);
config1.channelPerms.Add(config);
}
ServerConfig.UserCommandPermission commandperm;
if (config.userCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.UserID == id)).ToList().Count > 0)
{
commandperm = config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault();
config.userCommandPerms.Remove(commandperm);
}
else
{
await u.Channel.SendMessage("Permissions UnSucksecksful");
}
config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
ServerConfig.WriteServerConfig(config1);
await u.Channel.SendMessage("Permissions Sucksecksful");
});
t.CreateCommand("commandrole").Description("Blacklists/Whitelists commands for certain role").Parameter("User").Parameter("Command").Parameter("Enabled").Do(async u => {
// List<char> input = u.GetArg("User").ToCharArray().ToList();
// input.RemoveAt(0);
// input.RemoveAt(0);
// input.RemoveAt(input.Count - 1);
// ulong id = ulong.Parse(String.Concat(input));
ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
if(config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
{
config = new ServerConfig.ChannelPermission(u.Channel.Id);
config1.channelPerms.Add(config);
}
ServerConfig.RoleCommandPermission commandperm;
if (config.roleCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.Role == u.GetArg("User"))).ToList().Count > 0)
{
commandperm = config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault();
commandperm.Role = u.GetArg("User");
commandperm.enabled = bool.Parse(u.GetArg("Enabled"));
config.roleCommandPerms[config.roleCommandPerms.IndexOf(config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault())] = commandperm;
}
else
{
config.roleCommandPerms.Add(new ServerConfig.RoleCommandPermission(u.GetArg("User"), u.GetArg("Command"), bool.Parse(u.GetArg("Enabled"))));
}
config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
ServerConfig.WriteServerConfig(config1);
await u.Channel.SendMessage("Permissions Sucksecksful");
});
t.CreateCommand("removecommandrole").Description("Removes a Blacklist/Whitelist command for certain role").Parameter("User").Parameter("Command").Do(async u => {
// List<char> input = u.GetArg("User").ToCharArray().ToList();
// input.RemoveAt(0);
// input.RemoveAt(0);
// input.RemoveAt(input.Count - 1);
// ulong id = ulong.Parse(String.Concat(input));
ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
{
config = new ServerConfig.ChannelPermission(u.Channel.Id);
config1.channelPerms.Add(config);
}
ServerConfig.RoleCommandPermission commandperm;
if (config.roleCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.Role == u.GetArg("User"))).ToList().Count > 0)
{
commandperm = config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault();
config.roleCommandPerms.Remove(commandperm);
}
else
{
await u.Channel.SendMessage("Permissions UnSucksecksful");
}
config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
ServerConfig.WriteServerConfig(config1);
await u.Channel.SendMessage("Permissions Sucksecksful");
});
});
});
_client.ExecuteAndWait(async ()=>{
await _client.Connect("MTcxNzEyMTAwMzE2NjEwNTYx.CfbSCw.saNJTaBcw4EN8nZjjlzhzuHzJFI");
//"[email protected]", "mushroom12345"
});
}
示例13: Main
static void Main() {
//load credentials from credentials.json
Credentials c;
try {
c = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
botMention = c.BotMention;
if (c.ForwardMessages != true)
Console.WriteLine("Not forwarding messages.");
else {
ForwardMessages = true;
Console.WriteLine("Forwarding messages.");
}
OwnerID = c.OwnerID;
password = c.Password;
} catch (Exception ex) {
Console.WriteLine("Failed to load stuff from credentials.json, RTFM");
Console.ReadKey();
return;
}
//create new discord client
client = new DiscordClient();
//create a command service
var commandService = new CommandService(new CommandServiceConfig {
CommandChar = null,
HelpMode = HelpMode.Disable
});
//init parse
if (c.ParseKey != null && c.ParseID != null && c.ParseID != "" && c.ParseKey != "") {
ParseClient.Initialize(c.ParseID, c.ParseKey);
//monitor commands for logging
stats_collector = new StatsCollector(commandService);
} else {
Console.WriteLine("Parse key and/or ID not found. Logging disabled.");
}
//reply to personal messages and forward if enabled.
client.MessageReceived += Client_MessageReceived;
//add command service
var commands = client.Services.Add<CommandService>(commandService);
//count commands ran
client.Commands().CommandExecuted += (s, e) => commandsRan++;
//create module service
var modules = client.Services.Add<ModuleService>(new ModuleService());
//add audio service
var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() {
Channels = 2,
EnableEncryption = false,
EnableMultiserver = true,
Bitrate = 128,
}));
//install modules
modules.Add(new Administration(), "Administration", ModuleFilter.None);
//run the bot
client.ExecuteAndWait(async () => {
await client.Connect(c.Username, c.Password);
Console.WriteLine("-----------------");
Console.WriteLine(GetStats());
Console.WriteLine("-----------------");
foreach (var serv in client.Servers) {
if ((OwnerUser = serv.GetUser(OwnerID)) != null)
return;
}
});
Console.WriteLine("Exiting...");
Console.ReadKey();
}
示例14: Start
public async void Start()
{
var settings = GlobalSettings.Load();
if (settings == null) return;
_client = new DiscordClient();
StartNet(settings.Port);
if (settings.usePokeSnipers)
{
pollPokesniperFeed();
}
_client.MessageReceived += async (s, e) =>
{
if (settings.ServerChannels.Any(x => x.Equals(e.Channel.Name.ToString(), StringComparison.OrdinalIgnoreCase)))
{
await relayMessageToClients(e.Message.Text, e.Channel.Name.ToString());
}
};
_client.ExecuteAndWait(async () =>
{
if (settings.useToken && settings.DiscordToken != null)
await _client.Connect(settings.DiscordToken);
else if (settings.DiscordUser != null && settings.DiscordPassword != null)
{
try
{
await _client.Connect(settings.DiscordUser, settings.DiscordPassword);
}
catch
{
Console.WriteLine("Failed to authroize Discord user! Check your config.json and try again.");
Console.ReadKey();
return;
}
}
else
{
Console.WriteLine("Please set your logins in the config.json first");
}
});
}
示例15: Start
private void Start(string[] args)
{
#if !DNXCORE50
Console.Title = $"{AppName} (Discord.Net v{DiscordConfig.LibVersion})";
#endif
GlobalSettings.Load();
_client = new DiscordClient(x =>
{
x.AppName = AppName;
x.AppUrl = AppUrl;
x.MessageCacheSize = 0;
x.UsePermissionsCache = true;
x.EnablePreUpdateEvents = true;
x.LogLevel = LogSeverity.Debug;
x.LogHandler = OnLogMessage;
})
.UsingCommands(x =>
{
x.AllowMentionPrefix = true;
x.HelpMode = HelpMode.Public;
x.ExecuteHandler = OnCommandExecuted;
x.ErrorHandler = OnCommandError;
})
.UsingModules()
.UsingAudio(x =>
{
x.Mode = AudioMode.Outgoing;
x.EnableMultiserver = true;
x.EnableEncryption = true;
x.Bitrate = AudioServiceConfig.MaxBitrate;
x.BufferLength = 10000;
})
.UsingPermissionLevels(PermissionResolver);
_client.AddService<SettingsService>();
_client.AddService<HttpService>();
_client.AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist);
_client.AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist);
_client.AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist);
_client.AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist);
_client.AddModule<ModulesModule>("Modules", ModuleFilter.None);
_client.AddModule<PublicModule>("Public", ModuleFilter.None);
_client.AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist);
_client.AddModule<StatusModule>("Status", ModuleFilter.ServerWhitelist);
//_client.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist);
#if PRIVATE
PrivateModules.Install(_client);
#endif
//Convert this method to an async function and connect to the server
//DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end
//Note: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function.
_client.ExecuteAndWait(async () =>
{
while (true)
{
try
{
await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password);
_client.SetGame("Discord.Net");
//await _client.ClientAPI.Send(new Discord.API.Client.Rest.HealthRequest());
break;
}
catch (Exception ex)
{
_client.Log.Error($"Login Failed", ex);
await Task.Delay(_client.Config.FailedReconnectDelay);
}
}
});
}