node.js gbk編碼_如何使用Node.js將Chrome的霸王龍編碼為電報游戲

node.js gbk編碼

by Fernando García álvarez

通過費爾南多·加西亞·阿爾瓦雷斯

如何使用Node.js將Chrome的霸王龍編碼為電報游戲 (How to code Chrome’s T-Rex as a Telegram game using Node.js)

Last month I was really interested in learning how the Telegram game platform works. And as I was also really bored of playing Chrome’s T-Rex game alone, I decided to make it work as a Telegram game.

上個月,我對學習Telegram游戲平臺的工作方式非常感興趣。 而且,由于我也對獨自玩Chrome的T-Rex游戲感到非常無聊,因此我決定將其作為Telegram游戲使用。

While developing it I noticed there weren’t many Telegram game bot tutorials. Tutorial would explain the whole process of building it, from start to finish. So I decided to write about it.

在開發它時,我注意到并沒有太多Telegram游戲機器人教程。 教程將從頭到尾說明構建它的整個過程。 因此,我決定寫這篇文章。

If you want to see the result, the game is available as trexjumpbot in Telegram and is hosted here.

如果您想查看結果,可以在Telegram中以trexjumpbot的形式獲得該游戲, 并在此處托管。

要求 (Requirements)

You need to have Node.js installed

您需要安裝Node.js

第1步:創建我們的機器人 (Step 1: Creating our bot)

In order to create a game, we must first create an inline bot. We do this by talking to BotFather and sending the command

為了創建游戲,我們必須首先創建一個嵌入式機器人。 我們通過與BotFather交談并發送命令來做到這一點

/newbot

/newbot

Then, we are asked to enter a name and a username for our bot and we are given an API token. We need to save it as we will need it later.

然后,要求我們輸入機器人的名稱和用戶名,并獲得一個API令牌。 我們需要保存它,因為稍后將需要它。

We can also complete our bot info by changing its description (which will be shown when a user enters a chat with our bot under the “What can this bot do?” section) with

我們還可以通過更改其說明(當用戶在“此機器人可以做什么?”部分下與我們的機器人進行聊天時顯示)來完成我們的機器人信息。

/setdescription

/setdescription

And also set its picture, in order to make it distinguishable from the chat list. The image must be square and we can set it with the following command:

并設置其圖片,以使其與聊天列表區分開。 圖片必須為正方形,我們可以使用以下命令進行設置:

/setuserpic

/setuserpic

We can also set the about text, which will appear on the bot’s profile page and also when sharing it with other users

我們還可以設置About文本,該文本將顯示在機器人的個人資料頁面上以及與其他用戶共享時

/setabouttext

/setabouttext

Our bot has to be inline in order to be able to use it for our game. In order to do this, we simply have to execute the following and follow the instructions

我們的機器人必須是內聯的,以便能夠在我們的游戲中使用它。 為此,我們只需執行以下步驟并按照說明進行操作

/setinline

/setinline

步驟2:建立游戲 (Step 2: Creating our game)

Now that we have our inline bot completely set up, it’s time to ask BotFather to create a game:

現在我們已經完全設置了內聯機器人,現在是時候讓BotFather創建游戲了:

/newgame

/newgame

We simply follow the instructions and finally we have to specify a short name for our game. This will act as a unique identifier for it, which we will need later along with our bot API token

我們只需按照說明進行操作,最后我們必須為我們的游戲指定一個簡短的名稱。 這將充當它的唯一標識符,我們稍后將需要它以及bot API令牌

步驟3:獲取T-Rex游戲源代碼 (Step 3: Getting T-Rex game source code)

As Chromium is open source, some users have extracted the T-Rex game from it and we can easily find its source code online.

由于Chromium是開源的,因此一些用戶已經從中提取了T-Rex游戲,我們可以輕松地在網上找到其源代碼。

In order to make the game, I have used the code available in this GitHub repo, so go ahead and clone it:

為了制作游戲,我使用了此GitHub存儲庫中可用的代碼,因此繼續進行克隆:

git clone https://github.com/wayou/t-rex-runner.git

步驟4:設置依賴關系 (Step 4: Setting up dependencies)

First, go into the cloned folder and move all its files into a new folder called “public”

首先,進入克隆的文件夾,并將其所有文件移動到名為“ public”的新文件夾中

mkdir public && mv * public/.

And init the project

并啟動項目

npm init

You can fill the requested info as you want (you can leave the default values), leave the entry point as index.js

您可以根據需要填寫所需的信息(可以保留默認值),將入口點保留為index.js

We will need Express and node-telegram-bot-api in order to easily interact with Telegram’s API

我們將需要Express和node-telegram-bot-api以便輕松與Telegram的API進行交互

npm install express --savenpm install node-telegram-bot-api --save

We are going to add a start script, since it’s necessary in order to deploy the game to Heroku. Open package.json and add the start script under the scripts section:

我們將添加一個啟動腳本,因為將游戲部署到Heroku是必需的。 打開package.json并在腳本部分下添加啟動腳本:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
}

第5步:對服務器進行編碼 (Step 5: Coding our server)

Now that we have all dependencies set up, it’s time to code the server for our bot. Go ahead and create the index.js file:

現在我們已經設置了所有依賴項,是時候為我們的機器人編寫服務器代碼了。 繼續創建index.js文件:

const express = require("express");
const path = require("path");
const TelegramBot = require("node-telegram-bot-api");
const TOKEN = "YOUR_API_TOKEN_GOES_HERE";
const server = express();
const bot = new TelegramBot(TOKEN, { polling: true } );
const port = process.env.PORT || 5000;
const gameName = "SHORT_NAME_YOUR_GAME";
const queries = {};

The code above is pretty straightforward. We simply require our dependencies and set the token we got from BotFather and also the short name we defined as the game identifier. Also, we set up the port, initialize Express and declare a queries empty object. This will act as a map to store the Telegram user object under his id, in order to retrieve it later.

上面的代碼非常簡單。 我們只需要我們的依賴關系,并設置從BotFather獲得的令牌,以及我們定義為游戲標識符的簡稱。 同樣,我們設置端口,初始化Express并聲明一個查詢為空的對象。 這將用作將電報用戶對象存儲在其ID下的映射,以便以后檢索。

Next, we need to make the contents of the public directory available as static files

接下來,我們需要將公共目錄的內容作為靜態文件提供

server.use(express.static(path.join(__dirname, 'public')));

Now we are going to start defining our bot logic. First, let’s code the /help command

現在,我們將開始定義機器人邏輯。 首先,讓我們編寫/ help命令的代碼

bot.onText(/help/, (msg) => bot.sendMessage(msg.from.id, "This bot implements a T-Rex jumping game. Say /game if you want to play."));

We have to specify the command as a regex on the first parameter of onText and then specify the bot’s reply with sendMessage. Note we can access the user id in order to reply by using msg.from.id

我們必須在onText的第一個參數上將命令指定為正則表達式,然后使用sendMessage指定漫游器的回復。 請注意,我們可以使用msg.from.id來訪問用戶ID以便進行回復

When our bot receives the /start or /game command we are going to send the game to the user using bot.sendGame

當我們的機器人收到/ start或/ game命令時,我們將使用bot.sendGame將游戲發送給用戶

bot.onText(/start|game/, (msg) => bot.sendGame(msg.from.id, gameName));

Now the user will be shown the game’s title, his high score and a button to play it, but the play button still doesn’t work. So, we are going to implement its logic

現在,將向用戶顯示游戲的標題,他的高分和一個播放游戲的按鈕,但是播放按鈕仍然不起作用。 因此,我們將執行其邏輯

bot.on("callback_query", function (query) {
if (query.game_short_name !== gameName) {
bot.answerCallbackQuery(query.id, "Sorry, '" + query.game_short_name + "' is not available.");
} else {
queries[query.id] = query;
let gameurl = "https://YOUR_URL_HERE/index.html?  id="+query.id;
bot.answerCallbackQuery({
callback_query_id: query.id,
url: gameurl
});
}
});

When the user clicks the play button Telegram sends us a callback. In the code above when we receive this callback first we check that the requested game is, in fact, our game, and if not we show an error to the user.

當用戶單擊播放按鈕時,Telegram向我們發送回叫。 在上面的代碼中,當我們首先收到此回調時,我們檢查所請求的游戲是否確實是我們的游戲,如果沒有,則向用戶顯示錯誤。

If all is correct, we store the query into the queries object defined earlier under its id, in order to retrieve it later to set the high score if necessary. Then we need to answer the callback by providing the game’s URL. Later we are going to upload it to Heroku so you’ll have to enter the URL here. Note that I’m passing the id as a query parameter in the URL, in order to be able to set a high score.

如果一切正確,我們會將查詢存儲到先前在其ID下定義的查詢對象中,以便稍后進行檢索以在必要時設置高分。 然后,我們需要通過提供游戲的網址來回答回調。 稍后,我們將其上傳到Heroku,因此您必須在此處輸入URL。 請注意,我將id作為查詢參數傳遞給URL,以便能夠設置較高的分數。

Right now we have a fully functional game but we still are missing high scores and inline behavior. Let’s start with implementing inline and offering our game:

目前,我們有一個功能齊全的游戲,但我們仍然缺少高分和內聯行為。 讓我們從內聯實現和提供游戲開始:

bot.on("inline_query", function(iq) {
bot.answerInlineQuery(iq.id, [ { type: "game", id: "0", game_short_name: gameName } ] );
});

Last, we are going to implement the high score logic:

最后,我們將實現高分邏輯:

server.get("/highscore/:score", function(req, res, next) {
if (!Object.hasOwnProperty.call(queries, req.query.id)) return   next();
let query = queries[req.query.id];
let options;
if (query.message) {
options = {
chat_id: query.message.chat.id,
message_id: query.message.message_id
};
} else {
options = {
inline_message_id: query.inline_message_id
};
}
bot.setGameScore(query.from.id, parseInt(req.params.score),  options,
function (err, result) {});
});

In the code above, we listen for URLs like /highscore/300?id=5721. We simply retrieve the user from the queries object given its id (if it exists) and the use bot.setGameScore to send the high score to Telegram. The options object is different if the user is calling the bot inline or not, so we check both situations as defined in the Telegram Bot API

在上面的代碼中,我們偵聽/ highscore / 300?id = 5721之類的URL。 我們只需從查詢對象中檢索給定其ID(如果存在)的用戶,并使用bot.setGameScore將高分發送給Telegram。 如果用戶是否內聯調用bot,options對象是不同的,因此我們檢查了Telegram Bot API中定義的兩種情況

The last thing we have to do on our server is to simply listen in the previously defined port:

我們在服務器上要做的最后一件事就是簡單地偵聽先前定義的端口:

server.listen(port);

第6步:修改霸王龍游戲 (Step 6: Modifying T-Rex game)

We have to modify the T-Rex game we cloned from the GitHub repo in order for it to send the high score to our server.

我們必須修改從GitHub存儲庫中克隆的T-Rex游戲,以將高分發送給我們的服務器。

Open the index.js file under the public folder, and at the top of it add the following lines in order to retrieve the player id from the url:

打開公用文件夾下的index.js文件,并在其頂部添加以下行,以便從url中檢索播放器ID:

var url = new URL(location.href);
var playerid = url.searchParams.get("id");

Last, we are going to locate the setHighScore function and add the following code to the end of it, in order to submit the high score to our server:

最后,我們將定位setHighScore函數并將以下代碼添加到它的末尾,以便將高分提交給我們的服務器:

// Submit highscore to Telegram
var xmlhttp = new XMLHttpRequest();
var url = "https://YOUR_URL_HERE/highscore/" + distance  +
"?id=" + playerid;
xmlhttp.open("GET", url, true);
xmlhttp.send();

步驟7:部署到Heroku (Step 7: Deploying to Heroku)

Our game is complete, but without uploading it to a server we can’t test it on Telegram, and Heroku provides us a very straightforward way to upload it.

我們的游戲已經完成,但是沒有將其上傳到服務器,就無法在Telegram上對其進行測試,而Heroku為我們提供了一種非常簡單的上傳方式。

Start by creating a new app:

首先創建一個新應用:

Change our URL placeholders with the actual URL (replace with your own):

用實際的URL更改我們的URL占位符(用您自己的URL代替):

Replace the URL with the setHighScore function

用setHighScore函數替換URL

var url = "https://trexgame.herokuapp.com/highscore/" + distance +
"?id=" + playerid;

And also on the callback on the server:

以及服務器上的回調:

let gameurl = "https://trexgame.herokuapp.com/index.html?id="+query.id;

Finally, let’s upload our game to Heroku. Let’s follow the steps detailed on the Heroku page: After installing Heroku CLI, from the project folder login and push the files:

最后,讓我們將游戲上傳到Heroku。 讓我們按照Heroku頁面上詳述的步驟進行操作:安裝Heroku CLI后 ,從項目文件夾登錄并推送文件:

heroku logingit initheroku git:remote -a YOUR_HEROKU_APP_NAMEgit add .git commit -m "initial commit"git push heroku master

And that’s it!, now you finally have a fully working Telegram game. Go ahead and try it!

就是這樣!現在,您終于有了一個可以正常運行的Telegram游戲。 繼續嘗試!

Full source code of this example is available on GitHub

該示例的完整源代碼可在GitHub上找到

參考文獻 (References)

  • http://wimi5.com/como-crear-un-bot-para-juegos-en-telegram-con-nodejs/

    http://wimi5.com/como-crear-un-bot-para-juegos-en-telegram-con-nodejs/

  • https://core.telegram.org/bots/api#setgamescore

    https://core.telegram.org/bots/api#setgamescore

  • https://github.com/wayou/t-rex-runner

    https://github.com/wayou/t-rex-runner

翻譯自: https://www.freecodecamp.org/news/how-to-code-chromes-t-rex-as-a-telegram-game-using-node-js-cbcf42f76f4b/

node.js gbk編碼

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394979.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394979.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394979.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

二進制文件更新程序_APR 6.17程序文件更新

蘭博基尼程序文件更新Lamborghini Huracan EURO MY2018 5.2L V10 DKBC 4T0907552L S0002 Stage 1 V1.1 [APR Mobile]奧迪程序文件更新Audi A3 / VW GTI NA MY2014 2.0TSI CNTC 5G0906259A S0001 Stage 1 V2.0.3 [2WD] [Single Program]Audi A3 / VW GTI NA MY2014 2.0TSI CNTC …

android 事件攔截 (Viewpager不可以左右滑動)

以前沒有做過真正的需求,所以從來沒有覺得事件攔截分發處理有什么好懂的。 現在做需求了,真的是什么需求都有,你作為開發都要去研究實現。比如說,只能點不能滑動的viewpager。其實這都可以不用viewpager了。直接用fragment的repl…

mysql安裝設置數據目錄下,linux下安裝mysql數據+配置

《linux下安裝mysql數據配置》由會員分享,可在線閱讀,更多相關《linux下安裝mysql數據配置(2頁珍藏版)》請在人人文庫網上搜索。1、Redhat下安裝MySQL數據庫 說明:安裝環境:本地VMWare虛擬機redhat MySQL安裝目錄:/hom…

力扣——k個一組翻轉鏈表

給出一個鏈表,每 k 個節點一組進行翻轉,并返回翻轉后的鏈表。 k 是一個正整數,它的值小于或等于鏈表的長度。如果節點總數不是 k 的整數倍,那么將最后剩余節點保持原有順序。 示例 : 給定這個鏈表:1->2->3->4…

撥盤Demo大賽,獲獎公布-20170710

2019獨角獸企業重金招聘Python工程師標準>>> 為了答謝微信小程序聯盟的新老會員,極樂科技支持舉辦的撥盤大賽終于落幕,本次大賽有662人關注,報名參賽8位,獲獎名單如下: ##一、獲得1000元現金獎勵的參賽者 會…

2018年編程語言排行榜_這是2018年學習的最佳編程語言

2018年編程語言排行榜by Alexander Petkov通過亞歷山大佩特科夫(Alexander Petkov) 這是2018年學習的最佳編程語言 (Here are the best programming languages to learn in 2018) This is the definitive guide for anyone wanting to choose the right programming language …

ZJUTACM

描述 這回是浙江工業大學的ACM程序設計競賽,歡迎你的到來!但是,請稍等!裁判Joe說了,必須正確回答他的問題,才可以看到PIPI的氣球MM,KUKU的氣球GG.Joe手上有7張卡片,每張卡片上有一個大寫字母,分別是Z,J,U,T,A,C,M.現在他開始表演魔術,每次只交換其中的兩張卡片.等表…

vscode 不能運行h5c3代碼_讓開發效率“飛起”的VS Code 插件

前言VSCode,是一個免費的、開源的跨平臺編輯器,也是我最滿意的編輯器之一。本文向大家推薦一些我喜歡的vscode插件,不出意外的話,這些插件將對你的工作效率提升有不小的幫助!GitLensVS Code中的 Git 體驗在易用性和完整性之間取得…

dedecms plus/download.php,dedecms教程:DedeCMS 5.7SP1 /plus/download.php url重定向漏

最近使用scanv網站體檢發現有DedeCMS 5.7SP1 /plus/download.php url重定向漏洞(如下圖),對比官方網站最新下載包發現該漏洞未進行補丁,但官方自身網站已經補上了,而官方演示站點均未補上。參考了下網上給出的漏洞原因和解決思路如下&#xf…

C language day1

2019獨角獸企業重金招聘Python工程師標準>>> http://www.eclipsecolorthemes.org/?viewtheme&id66設置eclispe編輯器主題 http://www.cnblogs.com/csulennon/p/4231405.html 配置黑色主題 Dogs.c 第一段代碼片段 /*Name : Dogs.cAuthor : MichaelV…

Xftp遠程連接出現“無法顯示文件夾”的問題補充

網上有很多朋友出現相同的問題,各位熱心網友都給出了自己的解決方案,其中大多數網友給出的解決方案都是:將Xftp更換成“被動連接模式”。但是很不幸的是,本人通過這種方式并沒有得到有效的解決,網上的各大方法都嘗試&a…

Bootstrap中水平排列的表單form-inline

1 <html>2 <head>3 <title>初識Bootstrap</title>4 <meta charset"utf-8">5 <meta name"viewport" content"widthdevice-width, initial-scale1.0">6 <link rel"stylesheet" href"http:/…

minio 授予永久訪問權限_應對 iOS 14 權限管理 應用手把手教你打開“所有照片”權限...

DoNews 11月3日消息(記者 劉文軒)蘋果在 iOS 14 中帶來全新的隱私管理功能&#xff0c;其中最亮眼的就是相冊權限方面&#xff0c;可以為應用程序授予單獨授予某張照片的訪問權限&#xff0c;無需交出整個相冊。作為 iOS 14 主推新功能之一&#xff0c;這項功能也很快得到開發者…

ios pusher使用_使用.NET和Pusher構建實時評論功能

ios pusher使用by Ogundipe Samuel由Ogundipe Samuel 使用.NET和Pusher構建實時評論功能 (Build a real-time commenting feature using .NET and Pusher) Today, we will build a mini-blog engine with live commentary features using .NET and Pusher.今天&#xff0c;我們…

計算機基礎,你知道藍屏的原因嗎

2019獨角獸企業重金招聘Python工程師標準>>> 電腦藍屏的現象是經常見到的一件家常便飯了&#xff0c;它是屬于突發事件&#xff0c;電腦藍屏讓我們猝手不及&#xff0c;很多時候是很讓人心煩。電腦藍屏首先要找到原因&#xff0c;然后進行維修。那么電腦藍屏到底是怎…

discuz admin.php無法登錄,忘記管理員密碼無法登錄Discuz后臺管理員的解決方法匯總...

Discuz管理員無法登陸后臺的情況有多種下面會對這些問題提供一些解決方法&#xff1b;也會有可以登陸前臺卻無法登陸后臺的一系列解決辦法&#xff0c;下面是無憂主機小編總結的其中方法&#xff0c;希望對大家有所幫助。1.管理員用戶組變為普通用戶組了 進入不了后臺&#xff…

D進制的A+B

/*題目描述 //注意像二進制的數位比較長&#xff0c;只能用數組來做 輸入兩個非負10進制整數A和B(<2 30-1)&#xff0c;輸出AB的D (1 < D < 10)進制數。 輸入描述: 輸入在一行中依次給出3個整數A、B和D。 輸出描述: 輸出AB的D進制數。 輸入例子: 123 45…

2個字節能存多少個16進制_Java語言中最大的整數再加1等于多少?看完秒懂

短文漲姿勢&#xff0c;看了不白看&#xff0c;不關注等啥&#xff1f;已知Java語言中int類型所能表示的最大整數為2147483647,請問以下代碼執行結果是什么&#xff1f;一部分人都會認為這段程序壓根就無法通過編譯&#xff0c;也有人認為&#xff0c;這段程序能夠通過編譯&…

擺脫加卡他卡_如何通過三個簡單的步驟擺脫“故事卡地獄”。

擺脫加卡他卡Your backlog is full of detailed user stories. Your team is no longer able to manage them, or rank them.您的待辦事項列表中包含詳細的用戶故事。 您的團隊不再能夠對其進行管理或排名。 You wonder what the product you’re building is all about. The …

套接字結構

套接字編程簡介 最近在看《UNIX網絡編程卷一》,算是寫的讀書筆記吧. IPv4套接字地址結構 IPv4套接字地址結構定義在 < netinet/in.h > 頭文件中.它以 sockaddr_in 命名.下面是它的結構體: struct in_addr {in_addr_t s_addr; 32位IPv4地址,網絡字節序 …