【问题标题】:Telegram - Node. Js handle multiple updates电报 - 节点。 Js处理多个更新
【发布时间】:2017-04-11 04:51:45
【问题描述】:

我正在电报上创建游戏,目前我遇到了同时处理多个更新的问题。我正在使用 node.js

例如我有这个代码

var TelegramBot = require('node-telegram-bot-api'),    
  bot = new TelegramBot("MY_TOKEN", {polling: true});

bot.onText(/^\/createroom/, function (res, match) {

//Here i have some logic, to check whether if the room already created or not
service.checkIfRoomExist(res) // this service here, will always return false, because of the simultaneously chat
.then (function(isExist) {
 if (isExist === false) {
  service.createRoom(res)
  .then (function() {

  });
 }
});



//it works fine, if player type "/createroom" not simultaneously

//but if more than 1 player type "/createroom" simultaneously, my logic here doesn't work, it will create multiple room

}

有解决这个问题的想法吗?

非常感谢,任何帮助将不胜感激

【问题讨论】:

  • 那么,你写了一些不能正常工作的代码?为什么不显示呢?
  • @Tomalak,请看我上面编辑的代码,谢谢
  • 您需要删除“存在”检查。编写一个创建房间(或失败)的函数并调用它。该函数应该在成功时返回一个房间对象或抛出一个错误。这样,第一个传入请求成功,第二个请求失败。
  • @Tomalak,对不起,我还是不明白。你的意思是,只需使用函数 createRoom 对吗?它总是会返回成功,对吗?我仍然不知道,一些同时聊天会导致 createRoom 功能失败。抱歉,还是不明白
  • 为什么“createRoom”函数总是返回成功?这甚至没有意义。它要么可以创建一个房间,要么不能。

标签: javascript node.js telegram telegram-bot


【解决方案1】:

您需要将唯一的聊天/用户 ID 链接到您的数据库以防止此类冲突。请参阅下面的代码和 cmets 了解如何操作。

var TelegramBot = require('node-telegram-bot-api'),
    bot = new TelegramBot("MY_TOKEN", {
        polling: true
    });

bot.onText(/^\/createroom/, function (res, match) {
    //use res.chat.id for groups and res.user.id for individuals
    service.checkIfRoomExist(res.chat.id).then(function (isExist) {
        if (isExist === false) {
            service.createRoom(res.chat.id).then(function () {
                bot.sendMessage(res.chat.id, 'Initializing game!')
                    // send game content here
            });
        }
        bot.sendMessage(res.chat.id, 'A game has already started in this group!')
    })
});

function checkIfRoomExist(id) {
    // Your logic here that checks in database if game has been created
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    相关资源
    最近更新 更多