Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

telegram - How to solve disturbance in my bot in c#?

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-Telegram, separately ?use of the bot and start bot,Puts the impact of what they played together.Game one person is caused a disturbance in next person game. for example: if john start my bot in Mobile and desired_word for john is Newyork and length=7 ,when sara start my bot in Mobile. Len_desiredwords for john for example Become to 5 .

library = NetTelegramBotApi 4.0.0 vs = 2013 v4;

Do not know what to do.

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
 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
 please Enter Next charachter
 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
 please Enter Next charachter
 desired_word ="+blank2 ");
                  await bot.MakeRequestAsync(q);
                  continue;
                }         

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




}

example :

john run and start my bot , my bot send for john in telegram:

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

John send by telegram one charachter A

text = A , if A correct Then Send bot to john

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

ok ?

Now is the time,sara run my bot and start. my bot send for sara in telegram:

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

Now , john send for bot,next charchater Z , my bot send for john in telegram:

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

!!!!

The groups telegram done in groups, as well as individually. maybe in group or maybe individually.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...