【问题标题】:How to solve disturbance in my bot in c#?如何在 C# 中解决我的机器人中的干扰?
【发布时间】:2017-05-22 00:43:52
【问题描述】:

我做了一个电报机器人。其实bot是个游戏,玩猜一些话。但是问题是当我把robots添加到两个不同的组(作为管理员)或者两个user-Telegram,分别用bot和start bot,把影响他们一起玩的东西。游戏一个人在下一个人游戏中引起干扰。例如:如果 john 在 Mobile 中启动我的机器人,并且 john 的desired_word 是 Newyork 并且 length=7 ,那么当 sara 在 Mobile 中启动我的机器人时。例如 john 的 Len_desiredwords 变为 5 。

库 = NetTelegramBotApi 4.0.0 vs = 2013 v4;

不知道该怎么办。

代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetTelegramBotApi;
using NetTelegramBotApi.Requests;
using NetTelegramBotApi.Types;
using System.Net.Http;
using System.Runtime.Remoting.Channels;
using System.Data;
using System.Data.SqlClient;
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;

namespace WordsBot
{


 class Program
  {
   private static string Token =".........";
   private static ReplyKeyboardMarkup Menu1;

     static void Main(string[] args)
        {

           Task.Run(() => RunBot());
            Console.ReadLine();
        }

    public static async Task RunBot()
        {

            var bot = new TelegramBot(Token);
           // var updates = await bot.MakeRequestAsync(new GetUpdates() { Offset = offset });



            var me = await bot.MakeRequestAsync(new GetMe());
            Console.WriteLine("User Name is {0}", me.Username);
            long offset = 0;
            int whilecount = 0;
            while (true)
            {

                Console.WriteLine("while is {0}", whilecount);
                whilecount += 1;

                var  updates = await bot.MakeRequestAsync(new GetUpdates() { Offset = offset });

                Console.WriteLine("Update Count is {0} ", updates.Count());
                Console.WriteLine("-------------------------------------");
                try
                {



     string desired_word = "";
     int Len_desiredwords = 0 ;
     char [] blank1='';
     string b1="";
     string [] blank2="";
     foreach (var update in updates)
       {
        var text = update.Message.Text;
        offset = update.Id + 1;
         if (Text == "/start")
         {
            ds_GetDersiredWords = DAL.Get_DersiredWords();
             dt_GetDersiredWords = ds_GetDersiredWords.Tables[0];
             desired_word=dt_GetDersiredWords.Rows[0][1].tostring();// get word random of db 
             Len_desiredwords = desired_word.Length; // count charachter of word
             blank1 = desired_word.tochararray();// string to chararray

             for (int ii=0;ii<Len_desiredwords;ii+)// insert charachter '_' in blank1
             {
                  blank1 [ii] = '_';
             }
             for (int jj=0;jj<Len_desiredwords;jj++ )
             {
                  blank2 = blank2 + blank1 [jj];
             }

             var q = new SendMessage(update.Message.Chat.Id, "please Enter one charachter\n desired_word ="+blank2 ); // send to user id in telegram message.
             await bot.MakeRequestAsync(q);
                         continue;
          }
          else if (Text.length==1) // if Text = one Character
          {
             for (int xx=0;xx<Len_desiredwords;xx++)
             {
                  if (blank1 [xx] =system.convert.char(text))// check if charachter entered is in blank1 chararray? or no?
                  {
                      correct= true;
                      index1 = xx;
                      blank1[index1] = System.Convert.ToChar(text);
                      for(int yy= 0 ;yy<Len_desiredwords;yy++)
                      {

                      blank2 = blank2 + blank1 [yy];
                      }

                  }
                  else
                   {
                      continue;
                   }

              }

              if (correct==true)
                {
                        var q = new SendMessage(u.Message.Chat.Id,(update.Message.Chat.Id, "correct\n please Enter Next charachter\n desired_word ="+blank2 ");
                        await bot.MakeRequestAsync(q);
                        continue;
                 }

              else if(correct!=true)  
                {


                  var q = new SendMessage(u.Message.Chat.Id,(update.Message.Chat.Id, "incorrect\n please Enter Next charachter\n desired_word ="+blank2 ");
                  await bot.MakeRequestAsync(q);
                  continue;
                }         

           }
          else
           {
             continue;
            }
        }
   catch (Exception ex)
   {
       continue;
   }
}




}

示例:

john 运行并启动我的机器人,我的机器人在电报中发送给 john:

- Welcome to Guess the word Game. 
- please Enter one charachter 
- desired_word  :  _ _ _ _ _ 
- You have 10 chances.

约翰用电报发送一个字符A

text = A ,如果 A 正确,则将机器人发送给 john

- Good , Correct Charachter John. 
- please Enter Next charachter 
- desired_word  :  _ _ A _ _ 
- You have 9 chances.

好的?

现在是时候了,sara 运行我的机器人并开始。我的机器人在电报中发送 sara:

- Welcome to Guess the word Game. 
- please Enter one charachter 
- desired_word  :  _ _ _ _ _ _ _ _ _ 
- You have 18 chances.

现在,john 发送给 bot,下一个字符 Z,我的 bot 在电报中发送给 john:

- Bad , False Charachter John. 
- please Enter Next charachter 
- desired_word  :  _ _ _ _ _ _ _ _ _
- You have 17 chances.

!!!!

团体电报以团体的形式进行,也可以单独进行。可能是集体,也可能是个人。

【问题讨论】:

  • 听起来两个玩家都在使用相同的机器人对象实例。确保每个用户都实例化了一个新的机器人类实例。如果您不清楚如何执行此操作,则需要在此处显示更多代码,以便我们了解您当前如何创建机器人。
  • 好的@AndyLamb,不知道怎么做。今天或明天编辑我的代码。但是你需要所有的代码吗?几乎我所有的代码都是这个值。
  • @AndyLamb 几乎所有我的代码编辑
  • 没有解决办法,@AndyLamb?
  • 为你编辑问题并完成

标签: c# telegram telegram-bot


【解决方案1】:

正如@Andy Lamb 在评论中所写,您的问题是您只管理一个“游戏”,因此每个玩家都相互互动。

您必须找到一种方法来识别每条消息的发送者,并为每个玩家管理一个“游戏”。

游戏对象应该是一个类的实例,维护与单人游戏相关的所有数据(例如,desired_word 等)。您的 while (true) 循环应该如下所示:

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.
  }
}

希望对你有帮助!

【讨论】:

  • 感谢@A.Cheiesa,测试你的答案并回来。编辑问题并完成。
  • var sender = GetSender(update); var game = RetrieveGameOrInit(sender);游戏.更新(更新);什么图书馆?我的代码没用,或者你只是想写一些应该做的事情。
  • 它们只是您必须执行的操作的描述性名称。我将用有关内部实现的一些细节来更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 2020-03-19
  • 2018-11-20
  • 2012-12-24
  • 1970-01-01
  • 2020-11-17
相关资源
最近更新 更多