当前位置: 首页>>代码示例>>C#>>正文


C# DiscordClient.SetGame方法代码示例

本文整理汇总了C#中Discord.DiscordClient.SetGame方法的典型用法代码示例。如果您正苦于以下问题:C# DiscordClient.SetGame方法的具体用法?C# DiscordClient.SetGame怎么用?C# DiscordClient.SetGame使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Discord.DiscordClient的用法示例。


在下文中一共展示了DiscordClient.SetGame方法的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);
                    }
                }
            });
        }
开发者ID:SorAnoHikari,项目名称:MilliaBot,代码行数:33,代码来源:1453330503$Program.cs

示例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));
             */
        });
        }
开发者ID:SorAnoHikari,项目名称:MilliaBot,代码行数:28,代码来源:1453329945$Program.cs

示例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);
             }
         }
     });
 }
开发者ID:SorAnoHikari,项目名称:MilliaBot,代码行数:20,代码来源:1453330569$Program.cs

示例4: StringBuilder

        void IModule.Install(ModuleManager manager)
        {
            _client = manager.Client;
            _client.MessageReceived +=
                (s, e) =>
                {
                    StringBuilder builder = new StringBuilder($"Msg: ");

                    if (e.Server != null)
                        builder.Append($"{e.Server.Name} ");

                    builder.Append(e.Channel.Name);

                    Logger.FormattedWrite(builder.ToString(), e.Message.ToString(),
                        ConsoleColor.White);
                };

            _io = _client.GetService<DataIoService>();

            manager.CreateCommands("", group =>
            {
                group.MinPermissions((int) PermissionLevel.BotOwner);

                group.CreateCommand("io save")
                    .Description("Saves data used by the bot.")
                    .Do(e => _io.Save());

                group.CreateCommand("io load")
                    .Description("Loads data that the bot loads at runtime.")
                    .Do(e => _io.Load());

                group.CreateCommand("set name")
                    .Description("Changes the name of the bot")
                    .Parameter("name", ParameterType.Unparsed)
                    .Do(async e => await _client.CurrentUser.Edit(Config.Pass, e.GetArg("name")));

                group.CreateCommand("set avatar")
                    .Description("Changes the avatar of the bot")
                    .Parameter("name")
                    .Do(async e =>
                    {
                        string avDir = Constants.DataFolderDir + e.GetArg("name");

                        using (FileStream stream = new FileStream(avDir, FileMode.Open))
                        {
                            ImageType type;
                            switch (Path.GetExtension(avDir))
                            {
                                case ".jpg":
                                case ".jpeg":
                                    type = ImageType.Jpeg;
                                    break;
                                case ".png":
                                    type = ImageType.Png;
                                    break;
                                default:
                                    return;
                            }

                            await _client.CurrentUser.Edit(Config.Pass, avatar: stream, avatarType: type);
                        }
                    });

                group.CreateCommand("set game")
                    .Description("Sets the current played game for the bot.")
                    .Parameter("game", ParameterType.Unparsed)
                    .Do(e => _client.SetGame(e.GetArg("game")));

                group.CreateCommand("killbot")
                    .Description("Kills the bot.")
                    .Do(x =>
                    {
                        _io.Save();
                        Environment.Exit(0);
                    });

                group.CreateCommand("gc")
                    .Description("Lists used memory, then collects it.")
                    .Do(async e =>
                    {
                        await PrintMemUsage(e);
                        await Collect(e);
                    });

                group.CreateCommand("gc collect")
                    .Description("Calls GC.Collect()")
                    .Do(async e => await Collect(e));

                group.CreateCommand("gencmdmd")
                    .AddCheck((cmd, usr, chnl) => !chnl.IsPrivate)
                    .Do(async e => await DiscordUtils.GenerateCommandMarkdown(_client));
            });

            manager.CreateDynCommands("", PermissionLevel.User, group =>
            {
                group.CreateCommand("join")
                    .Description("Joins a server by invite.")
                    .Parameter("invite")
                    .Do(async e => await DiscordUtils.JoinInvite(e.GetArg("invite"), e.Channel));

//.........这里部分代码省略.........
开发者ID:SSStormy,项目名称:Stormbot,代码行数:101,代码来源:BotManagementModule.cs

示例5: 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);
                    }
                }
            });
        }
开发者ID:Daxelman,项目名称:DiscordBot,代码行数:101,代码来源:Program.cs

示例6: 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);
                    }
                }
            });
        }
开发者ID:RogueException,项目名称:DiscordBot,代码行数:75,代码来源:Program.cs

示例7: ConnectAsync

        private static async void ConnectAsync()
        {
            State = ConnectionState.Connecting;

            Client = new DiscordClient();

            Client.MessageReceived += MessageHandler.HandleIncomingMessage;
            Client.MessageUpdated += MessageHandler.HandleEdit;

            Console.WriteLine("Connecting...");
            try
            {
                await Client.Connect(Config.Token, TokenType.Bot);
                Client.SetGame("3v.fi/l/BotVentic");
                State = ConnectionState.Connected;
                Console.WriteLine("Connected!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.WriteLine("Reconnecting...");
                State = ConnectionState.Disconnected;
                Client.Dispose();
            }
        }
开发者ID:3ventic,项目名称:BotVentic,代码行数:25,代码来源:Program.cs

示例8: Init

		async void Init()
		{
			Karuta.logger.Log("Starting Discord Bot..", _appName);
			try
			{
				ImgurSetup();
			}
			catch (Exception e)
			{
				Karuta.logger.LogError($"Unable to initiate Imgur Connection: {e.Message}", _appName);
			}
			client = new DiscordClient();
			if(string.IsNullOrWhiteSpace(_token))
			{
				_token = Karuta.GetInput("Enter discord token");
				Karuta.registry.SetValue("discordToken", _token);
			}

			client.MessageReceived += MessageRecieved;
			client.UserJoined += UserJoined;
			try
			{
				await client.Connect(_token, TokenType.Bot);
				client.SetGame("World Domination");
				//SendToAllConsoles("Bot Online");
			}catch(Exception e)
			{
				Karuta.logger.LogWarning($"Unable to initiate connection to discord: {e.Message}", _appName);
				Karuta.logger.LogError(e.StackTrace, _appName, true);
				Karuta.Write("Unable to connect to discord...");
			}
		}
开发者ID:TheDarkVoid,项目名称:Karuta,代码行数:32,代码来源:DiscordBot.cs

示例9: Connect

        private static async void Connect(DiscordClient inoriClient)
        {
            inoriClient.ExecuteAndWait(async () =>
            {
                while (true)
                {
                    try
                    {
                        await inoriClient.Connect(EMAIL, PASSWORD);
                        inoriClient.SetGame("Guilty Gear Xrd -Revelator-");
                        var channelName = "Koromo's Room";
                        var textChannelName = "Koromos_room";
                        OttawaAnimeCrewServer = inoriClient.Servers.FirstOrDefault(s => s.Name.Equals("Ottawa Anime Crew"));
                        TLSokuServer = inoriClient.Servers.FirstOrDefault(s => s.Name.Equals("TL Soku"));
                        VoiceChannel = TLSokuServer.VoiceChannels.FirstOrDefault(v => v.Name.Equals(channelName));
                        MusicChatChannel = TLSokuServer.TextChannels.FirstOrDefault(v => v.Name.Equals(textChannelName));
                        await VoiceChannel.JoinAudio();

                        break;
                    }
                    catch (Exception ex)
                    {
                        inoriClient.Log.Message += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex));
                        await Task.Delay(inoriClient.Config.FailedReconnectDelay);
                    }
                }
            });
        }
开发者ID:SorAnoHikari,项目名称:MilliaBot,代码行数:28,代码来源:MilliaBot.cs


注:本文中的Discord.DiscordClient.SetGame方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。