本文整理汇总了C#中Discord.DiscordClient.Run方法的典型用法代码示例。如果您正苦于以下问题:C# DiscordClient.Run方法的具体用法?C# DiscordClient.Run怎么用?C# DiscordClient.Run使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Discord.DiscordClient
的用法示例。
在下文中一共展示了DiscordClient.Run方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
var client = new DiscordClient();
//Display all log messages in the console
client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
//Echo back any message received, provided it didn't come from the bot itself
client.MessageReceived += async (s, e) =>
{
if (!e.Message.IsAuthor)
await client.SendMessage(e.Channel, e.Message.Text);
};
//Convert our sync method to an async one and block the Main function until the bot disconnects
client.Run(async () =>
{
while (true)
{
try
{
await client.Connect(EMAIL, PASSWORD);
await client.SetGame(1);
break;
}
catch (Exception ex)
{
client.LogMessage += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex));
await Task.Delay(client.Config.FailedReconnectDelay);
}
}
});
}
示例2: Main
static void Main(string[] args)
{
var client = new DiscordClient();
//Display all log messages in the console
client.LogMessage += (s, e) => Console.WriteLine("[{e.Severity}] {e.Source}: {e.Message}");
//Echo back any message received, provided it didn't come from the bot itself
client.MessageReceived += async (s, e) =>
{
if (!e.Message.IsAuthor)
await client.SendMessage(e.Channel, e.Message.Text);
};
//Convert our sync method to an async one and block the Main function until the bot disconnects
client.Run(async () =>
{
//Connect to the Discord server using our email and password
await client.Connect(EMAIL, PASSWORD);
client.SetGame(1);
//If we are not a member of any server, use our invite code (made beforehand in the official Discord Client)
/*
if (!client.AllServers.Any())
await client.AcceptInvite(client.GetInvite(TL_SOKU_INVITE_CODE));
*/
});
}
示例3: Connect
private async void Connect(DiscordClient inoriClient)
{
inoriClient.Run(async () =>
{
while (true)
{
try
{
await inoriClient.Connect(EMAIL, PASSWORD);
await inoriClient.SetGame(1);
break;
}
catch (Exception ex)
{
inoriClient.LogMessage += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex));
await Task.Delay(inoriClient.Config.FailedReconnectDelay);
}
}
});
}
示例4: 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.GoogleAPIKey == null || c.GoogleAPIKey == "") {
Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
} else {
GoogleAPIKey = c.GoogleAPIKey;
}
OwnerID = c.OwnerID;
password = c.Password;
}
catch (Exception)
{
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. Bot will not log.");
}
//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
}));
//install modules
modules.Install(new Administration(), "Administration", FilterType.Unrestricted);
modules.Install(new Conversations(), "Conversations", FilterType.Unrestricted);
modules.Install(new Gambling(), "Gambling", FilterType.Unrestricted);
modules.Install(new Games(), "Games", FilterType.Unrestricted);
modules.Install(new Music(), "Music", FilterType.Unrestricted);
modules.Install(new Searches(), "Searches", FilterType.Unrestricted);
//run the bot
client.Run(async () =>
{
await client.Connect(c.Username, c.Password);
Console.WriteLine("Connected!");
});
Console.WriteLine("Exiting...");
Console.ReadKey();
}
示例5: Main
//.........这里部分代码省略.........
string finalstr = "";
for (int i = 2; i < splitmessage.Length; i++)
{
if (i != 2)
finalstr += ' ' + splitmessage[i];
else
finalstr = splitmessage[i];
}
if (finalstr.Length > 5)
{
kardFactsStrings.Add(finalstr);
await client.SendMessage(currentChannel, "A new fact about Kard has been added. (Yay ^-^):");
currentChannel = e.Channel;
await client.SendMessage(currentChannel, finalstr);
}
else
{
throw new IOException("Hue.");
}
}
catch (Exception)
{
await client.SendMessage(currentChannel, "That hurt <.< Don't do this again, ok? :3");
}
}
}
else
{
await client.SendMessage(currentChannel, kardFacts());
}
}
else if (e.Message.Text.StartsWith("-play"))
{
Task.Run(() => { PlaySoundWav(e); });
}
else if(e.Message.Text.StartsWith("-getclientid"))
{
if (e.Message.Text.Length > "-getclientid ".Length)
{
try {
await client.SendMessage(currentChannel, e.Server.Members.Where((User u) =>
{
return u.Name.StartsWith(e.Message.Text.Substring("-getclientid ".Length));
}).First().Id.ToString());
}
catch(Exception)
{
await client.SendMessage(currentChannel, "User does not exist. B-baka.");
}
}
else
{
await client.SendMessage(currentChannel, e.Message.User.Id.ToString());
}
}
else if(e.Message.Text.StartsWith(":"))
{
await rpg.HandleCommands(e, client, currentChannel);
}
else if (await handleSimpleCommands(e, client, currentChannel) == false)
{
await handleTiroCommands(e, client, currentChannel);
}
}
示例6: 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(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: Run is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function.
_client.Run(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);
}
}
});
}
示例7: Start
private static void Start()
{
SettingsManager.Load();
_client = new DiscordClient();
_client.LogMessage += (s, e) =>
{
Console.WriteLine($"[{e.Severity}] {e.Source} => {e.Message}");
};
//Set up permissions
_client.AddService(new BlacklistService());
_client.AddService(new WhitelistService());
_client.AddService(new PermissionLevelService((u, c) =>
{
if (u.Id == long.Parse(SettingsManager.OwnerID))
return (int)PermissionLevel.BotOwner;
if (!u.IsPrivate)
{
if (u == c.Server.Owner)
return (int)PermissionLevel.ServerOwner;
var serverPerms = u.GetServerPermissions();
if (serverPerms.ManageRoles)
return (int)PermissionLevel.ServerAdmin;
if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers)
return (int)PermissionLevel.ServerMod;
var channelPerms = u.GetPermissions(c);
if (channelPerms.ManagePermissions)
return (int)PermissionLevel.ChannelAdmin;
if (channelPerms.ManageMessages)
return (int)PermissionLevel.ChannelMod;
}
return (int)PermissionLevel.User;
}));
//Set up commands
var commands = _client.AddService(new CommandService(new CommandServiceConfig
{
CommandChar = '!',
HelpMode = HelpMode.Private
}));
commands.RanCommand += (s, e) => Console.WriteLine($"[Command] {(e.Server == null ? "[Private]" : e.Server.ToString()) + "/" + e.Channel} => {e.Message}");
commands.CommandError += (s, e) =>
{
string msg = e.Exception?.GetBaseException().Message;
if (msg == null)
{
{
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.SendMessage(e.Channel, $"Failed to complete command: {msg}");
Console.WriteLine($"[Error] Failed to complete command: {e.Command?.Text} for {e.User?.Name}");
Console.WriteLine($"Command failure: {msg}");
}
};
//Set up modules
var modules = _client.AddService(new ModuleService());
//Boot up
_client.Run(async () =>
{
while (true)
{
try
{
await _client.Connect(SettingsManager.Email, SettingsManager.Password);
if (!_client.AllServers.Any())
await _client.AcceptInvite(_client.GetInvite("0nwaapOqh2LPqDL9").Result);
modules.Install(new Modules.SimpleCommands(), "Simple Commands", FilterType.Unrestricted);
modules.Install(new Modules.Chance(), "Dice Rolling", FilterType.Unrestricted);
break;
}
catch (Exception ex)
{
Console.WriteLine("Login failed" + ex.ToString());
//.........这里部分代码省略.........
示例8: Run
public void Run()
{
ReadConfig();
VerifyReady();
Thread t = new Thread(() =>
{
f = new EasyMusicBot.Form1(this);
Application.EnableVisualStyles();
Application.Run(f);
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
Client = new DiscordClient(new DiscordConfig
{
AppName = "Easy Music Bot",
AppUrl = "Put url here",
//AppVersion = DiscordConfig.LibVersion,
LogLevel = LogSeverity.Info,
MessageCacheSize = 0,
UsePermissionsCache = false
});
VidLoopAsync();
Client.Connected += (s, e) => {
Console.WriteLine("Connected to Discord with email " + email);
//Client.SetGame(null);
foreach (Discord.Channel c in Client.GetServer(104979971667197952).TextChannels)
{
if (c.Name.Equals(Channel))
{
//MessageBox.Show("che set to " + c.Name);
DChannel = c;
}
}
};
Client.MessageReceived += (s, e) =>
{
LRC = e.Message.Channel;
Console.WriteLine("Message recieved!");
InterpretCommand(e.Message);
};
try
{
Client.Run(async () =>
{
await Client.Connect(email, password);
});
}
catch (Exception e)
{
Console.WriteLine("Oh noes! There seems to be a problem with conencting to Discord!");
Console.WriteLine("Make sure you typed the email and password fields correctly in the config.txt");
Console.WriteLine("If you happen across the developer, make sure to tell him this: " + e.Message);
}
MessageBox.Show("t");
}
示例9: Main
static void Main(string[] args)
{
// Load up the DB, or create it if it doesn't exist
SQL.LoadDB();
// Load up the config file
LoadConfig();
Console.Title = $"Nekobot v{version}";
// Load the stream channels
Music.LoadStreams();
// Initialize rest client
RCInit();
client = new DiscordClient(new DiscordClientConfig
{
AckMessages = true,
LogLevel = LogMessageSeverity.Verbose,
TrackActivity = true,
UseMessageQueue = false,
UseLargeThreshold = true,
EnableVoiceMultiserver = true,
VoiceMode = DiscordVoiceMode.Outgoing,
});
// Set up the events and enforce use of the command prefix
commands.CommandError += CommandError;
client.Connected += Connected;
client.Disconnected += Disconnected;
client.UserJoined += UserJoined;
client.LogMessage += LogMessage;
client.AddService(commands);
client.AddService(new PermissionLevelService(GetPermissions));
commands.CreateGroup("", group => GenerateCommands(group));
commands.NonCommands += Chatbot.Do;
// Load the chatbots
Chatbot.Load();
// Keep the window open in case of crashes elsewhere... (hopefully)
Thread input = new Thread(InputThread);
input.Start();
// Connection, join server if there is one in config, and start music streams
try
{
client.Run(async() =>
{
await client.Connect(config["email"].ToString(), config["password"].ToString());
if (config["server"].ToString() != "")
{
await client.AcceptInvite(client.GetInvite(config["server"].ToString()).Result);
}
await Music.StartStreams();
});
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.GetBaseException().Message}");
}
}