如何解决 C# 中机器人的干扰问题?

2024-04-07

我做了一个电报机器人。事实上,机器人是一个游戏,玩猜某些单词。但问题是当我将机器人添加到两个不同的组(作为管理员)或两个用户-Telegram,分别使用机器人和启动机器人时,会产生影响一个人的游戏对下一个人的游戏造成干扰。例如:如果 john 在 Mobile 中启动我的机器人,并且 john 的desired_word 是 Newyork 并且 length=7 ,那么当 sara 在 Mobile 中启动我的机器人时。例如 john 的 Len_desiredwords 变为 5 。

库 = NetTelegramBotApi 4.0.0 vs = 2013 v4;

不知该怎样。

code:

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




}

例子 :

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

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

ok ?

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

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

现在,约翰发送给机器人,下一个字符是,我的机器人在电报中发送给约翰:

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

!!!!

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


正如@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.
  }
}

希望能帮助到你!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何解决 C# 中机器人的干扰问题? 的相关文章

  • 套接字编程-listen() 和accept() 有什么区别?

    我一直在读本教程 http www cs rpi edu moorthy Courses os98 Pgms socket html了解套接字编程 看来listen and accept 系统调用都做同样的事情 即阻塞并等待客户端连接到使用
  • 显示 div 内的用户名列表

    我是 jQuery 新手 在我的项目中 我创建了一个类User其中代码如下所示 static ConcurrentDictionary
  • 在异步请求中使用超时回调

    我之前问过这个问题 但我将用提出的解决方案来完成这个问题 并提出另一个问题 我正在使用这个类来进行异步网络请求 http msdn microsoft com en us library system net webrequest aspx
  • 何时使用 C++ 私有继承而不是组合?

    你能给我一个具体的例子吗 什么时候使用私有继承优于组合 就我个人而言 我将使用组合而不是私有继承 但在某些情况下 使用私有继承可能是特定问题的最佳解决方案 正在阅读C faq http www parashift com c faq lit
  • C语言中没有循环可以打印数组吗?

    例如 在Python中 如果我们将一个列表作为数组 它会直接用一行代码打印整个数组 有什么办法可以用C语言实现同样的事情吗 简短回答 No 对表格上几乎所有问题的简短回答 用 C 语言做 X 工作能像用 Python 一样简单吗 No 长答
  • c 使用 lseek 以相反顺序复制文件

    我已经知道如何从一开始就将一个文件复制到另一个文件 但是我如何修改程序以按相反的顺序复制它 源文件应具有读取访问权限 目标文件应具有读写执行权限 我必须使用文件控制库 例如 FILE A File B should be ABCDEF FE
  • PartialView Action 正在调用自身

    我有 MVC 应用程序 它用于从主视图 ProductMaster 将 ProductAreaGrid 列表显示为 PartialView 并且它将在局部视图内将 CreateProductArea 作为 PartialView 我的 Gr
  • 应用新设置时如何防止 GraphicsDevice 被丢弃?

    我的游戏窗口允许手动调整大小 这意味着它可以像任何其他普通窗口一样通过拖动其边缘来调整大小 游戏还利用了RenderTarget2D rt2d 在主 Draw 方法中设置主渲染目标 GraphicsDevice SetRenderTarge
  • 多个线程访问一个变量

    我在正在读的一本教科书中发现了这个问题 下面也给出了解决方案 我无法理解最小值怎么可能是 2 为什么一个线程不能读取 0 而所有其他线程都执行并写入 1 而无论是1还是2 最后写入的线程仍然必须完成自己的循环 int n 0 int mai
  • 为什么 rand() 总是返回相同的值? [复制]

    这个问题在这里已经有答案了 可能的重复 在C中生成随机数 https stackoverflow com questions 3067364 generating random numbers in c 使用 rand 生成随机数 http
  • 使用 catch all 字典属性将 json 序列化为对象

    我想使用 JSON net 反序列化为对象 但将未映射的属性放入字典属性中 是否可以 例如给定 json one 1 two 2 three 3 和 C 类 public class Mapped public int One get se
  • C# 反序列化过程中创建指向父对象的指针

    我有这样的课程 Serializable public class child public Parent parent Serializable public class Parent public List
  • 如果项目包含多个文件夹,如何使用 Add-Migration

    我想Add Migration使用我的 DbContext 但出现错误 The term add migration is not recognized as the name of a cmdlet function script fil
  • XCode std::thread C++

    对于学校的一个小项目 我需要创建一个简单的客户端 服务器结构 它将在路由器上运行 使用 openWRT 并且我试图在这个应用程序中使用线程做一些事情 我的 C 技能非常有限 所以我在internet https stackoverflow
  • 如何使 WinForms UserControl 填充其容器的大小

    我正在尝试创建一个多布局主屏幕应用程序 我在顶部有一些按钮链接到应用程序的主要部分 例如模型中每个实体的管理窗口 单击这些按钮中的任何一个都会在面板中显示关联的用户控件 面板包含用户控件 而用户控件又包含用户界面 WinForms User
  • 在 C# 窗口应用程序中运行 C/C++ 控制台应用程序?

    现在 我想开发一个简单的应用程序 因此我决定最快的编码方式是 C NET 但现在 我很难实现我需要的功能之一 我想做的是在 C 应用程序的窗口内运行 C C 控制台应用程序 就像在虚幻前端中一样 添加一点通信方式 以便我可以为控制台应用程序
  • 如何使用“路径”查询 XDocument?

    我想查询一个XDocument给定路径的对象 例如 path to element I want 但我不知道如何继续 您可以使用以下方法System Xml XPath Extensions http msdn microsoft com
  • C# 模式匹配

    我对 C 有点陌生 我正在寻找一个字符串匹配模式来执行以下操作 我有一个像这样的字符串 该书将在 唐宁街 11 号接待处 并将由主要医疗保健人员参加 我需要创建一个 span 标签来使用 startIndex 和 length 突出显示一些
  • 使用方法的状态模式

    我正在尝试使用方法作为状态而不是类来基于状态模式的修改版本来实现一个简单的状态机 如下所示 private Action
  • 查找和替换正则表达式问题

    感谢这里对我其他问题的所有大力帮助 我开始掌握正则表达式 但我仍然对这个一无所知 我的代码是 StreamReader reader new StreamReader fDialog FileName ToString string con

随机推荐