How to solve disturbance in my bot in c#?

后端 未结 1 1035
不思量自难忘°
不思量自难忘° 2020-11-28 16:38

I made a telegram Bot. In fact, the bot is a game, play guess certain words.But the problem is when I add robots to two different groups (as an administrator) or Two user-Te

相关标签:
1条回答
  • 2020-11-28 17:06

    As @Andy Lamb wrote in a comment, your problem is that you are managing only one "game", so every player interacts with each other.

    You must find a way to identify the sender of each message, and manage a "game" for each player.

    A game object should be an instance of a class, maintaining all the data which is linked to a single player game (e.g. desired_word, etc). Your while (true) loop should look something like this:

    while (true) {
      var  updates = await bot.MakeRequestAsync(new GetUpdates() { Offset = offset });
      foreach(var update in updates) {
        var sender = GetSender(update);
        var game = RetrieveGameOrInit(sender);
    
        // ... rest of your processing, but your code is a little messy and
        // you have to figure out how to refactor the processing by yourself
        game.Update(update);
    
        // do something with game, and possibly remove it if it's over.
      }
    }
    
    
    public string GetSender(UpdateResponseOrSomething update)
    {
        // use the Telegram API to find a key to uniquely identify the sender of the message.
        // the string returned should be the unique identifier and it
        // could be an instance of another type, depending upon Telegram
        // API implementation: e.g. an int, or a Guid.
    }
    
    private Dictionary<string, Game> _runningGamesCache = new Dictionary<string, Game>();
    
    public Game RetrieveGameOrInit(string senderId)
    {
        if (!_runningGamesCache.ContainsKey(senderId))
        {
           _runningGamesCache[senderId] = InitGameForSender(senderId);
        }
    
        return _runningGamesCache[senderId];
    }
    
    /// Game.cs
    public class Game
    {
      public string SenderId { get; set; }
      public string DesiredWord { get; set; }
      // ... etc
    
      public void Update(UpdateResponseOrSomething update)
      {
        // manage the update of the game, as in your code.
      }
    }
    

    Hope it helps!

    0 讨论(0)
提交回复
热议问题