当前位置:   article > 正文

小试牛刀-Telebot区块链游戏机器人(TS升级)

小试牛刀-Telebot区块链游戏机器人(TS升级)

目录

1.编写目的

2.为什么使用TypeScript实现?

3.实现功能

3.1 AI图片生成

3.2 签到

3.3 邀请

3.4 WalletConnect连接

4.功能实现详解

4.1 AI图片生成

4.2 签到

4.3 邀请

4.4 WalletConnect连接

5.功能截图

​6.问题整理


Welcome to Code Block's blog

本篇文章主要介绍了

[Telebot区块链游戏机器人TS升级]
❤博主广交技术好友,喜欢文章的可以关注一下❤

1.编写目的

        本篇文章是小试牛刀-Telebot区块链游戏机器人(python版本)的typescript版本开发记录,实现该版本的主要目的是为了集成walletconnect,以实现用户wallet的无存储公私钥的交互功能.

2.为什么使用TypeScript实现?

        首先walletconnct对TypeScript有着良好的支持,它可以直接使用@walletconnect/sign-client中的组件对wc协议进行配对监听,方便后续的事务签名。而python几乎没有相关的组件库(也可能是我没找到).

        如果没有库,替代方法可以是python直接调用js文件,但这会让整个项目显得不伦不类.或者python去做request请求,请求部署的js文件服务.但这会让项目整体的稳定性变低.

        基于以上的种种考虑,所以这边将整个项目修改为TS版本.

3.实现功能

        实现的功能包括在小试牛刀-Telebot区块链游戏机器人已经实现的所有功能,将其集成到TS版本中.在此基础上,我又增加了以下功能:

3.1 AI图片生成

        用户可以通过输入/genimg+[描述]命令生成一张与描述相关的艺术画作图片.

3.2 签到

        用户可以每天进行签到以获得代币奖励.

3.3 邀请

        用户可以通过/shill命令生成邀请链接,并通过分享该链接在用户通过该链接使用机器人时获得代币奖励.

3.4 WalletConnect连接

      用户可以通过输入/wclink命令,获得walletconnect二维码,当用户通过支持walletconnect协议的钱包扫码时,可以连接到机器人.
        

4.功能实现详解

4.1 AI图片生成

        AI图片生成是通过huggingface上运行的AI模型接口实现(为什么不用国内的?答:少,且要钱).首先你需要在huggingface上注册一个token,当然如果你不想申请也可以直接用代码内的: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,然后使用post请求直接调用相关模型,具体使用方法可以在huggingface官网进行查看.

  1. import TelegramBot from 'node-telegram-bot-api';
  2. import { getCommandsText } from '../filter/Intercept'
  3. import axios from 'axios';
  4. // 定义 API_TOKEN 和数据接口
  5. const API_TOKEN: string = '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'; // 替换为你的 API Token
  6. interface QueryData {
  7. inputs: string;
  8. }
  9. // 处理分享链接命令
  10. async function handleGenImg(bot:TelegramBot,message: TelegramBot.Message): Promise<void> {
  11. const inviterUserId = message.from?.id;
  12. const username = message.from?.username;
  13. const text=getCommandsText(message);
  14. query({inputs:text})
  15. .then((response) => {
  16. const helpText="<b>Beautiful!\nThis is the image you created! @"+{username}+"</b>\n"
  17. bot.sendPhoto(message.chat.id, response, {
  18. caption: helpText,
  19. parse_mode: 'HTML'
  20. });
  21. })
  22. .catch((error) => {
  23. console.error('Error:', error);
  24. });
  25. }
  26. // 注册命令处理程序
  27. export function registerGenImgHandlers(bot:TelegramBot): void {
  28. bot.onText(/\/genimg/, async (msg) => {
  29. await handleGenImg(bot,msg);
  30. });
  31. }
  32. async function query(data: any): Promise<any> {
  33. try {
  34. const response = await axios.post(
  35. "https://api-inference.huggingface.co/models/alvdansen/littletinies",
  36. JSON.stringify(data),
  37. {
  38. headers: { Authorization: `Bearer ${API_TOKEN}` },
  39. responseType: 'arraybuffer'
  40. },
  41. );
  42. return response.data;
  43. } catch (error) {
  44. console.error('请求错误:', error);
  45. throw error;
  46. }
  47. }

4.2 签到

        用户签到即用户每天可点击一次按钮并获得奖励,这里注意用户点击后该用户id要进行记录,防止重复签到,实现代码如下:

  1. async function dailyCheck(bot: TelegramBot, call: TelegramBot.CallbackQuery) {
  2. const fromUserId = call.from.id;
  3. const username = call.from.username;
  4. //防止连续点击
  5. if (!passGameTime(fromUserId)) {
  6. bot.sendMessage(call.message!.chat.id, "<b>Please do not send duplicate messages</b>", { parse_mode: 'HTML' });
  7. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  8. return;
  9. }
  10. dailyCommandTime[fromUserId] = Date.now();
  11. if (await notHasWallet(String(fromUserId))) {
  12. bot.sendMessage(call.message!.chat.id, `<b>You not have wallet info, you need send [/create] create one game wallet! @${call.from.username}</b>`, { parse_mode: 'HTML' });
  13. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  14. return;
  15. }
  16. //限定签到数量
  17. if (await checkDailyNumber()) {
  18. bot.sendMessage(call.message!.chat.id, `<b>There are only 50 people per day, please come again tomorrow! @${call.from.username}</b>`, { parse_mode: 'HTML' });
  19. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  20. return;
  21. }
  22. if (await checkDaily(String(fromUserId))) {
  23. bot.sendMessage(call.message!.chat.id, `<b>You have already daily check! @${call.from.username}</b>`, { parse_mode: 'HTML' });
  24. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  25. return;
  26. }
  27. //发送奖励
  28. const [ amount, tx ] = await drawDailyCheck(String(SEND_USER_ID), String(fromUserId));
  29. if (tx === "error") {
  30. bot.sendMessage(call.message!.chat.id, "<b>Daily Check Error!</b>", { parse_mode: 'HTML' });
  31. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  32. return;
  33. }
  34. if (tx=="error:account"){
  35. bot.sendMessage(call.message!.chat.id, `<b>You must first send some BOGGY into the wallet before you can [DaliyCheck] and [invite] @${username}</b>`, { parse_mode: 'HTML' });
  36. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  37. return;
  38. }
  39. //添加每日签到数据
  40. addDaily(String(fromUserId));
  41. const markup = {
  42. inline_keyboard: [
  43. [
  44. { text: "Check Tx", url: `https://solscan.io/tx/${tx}` }
  45. ]
  46. ]
  47. };
  48. bot.sendMessage(call.message!.chat.id, `<b>The Daily Check amount ${amount} BOGGY transfer end, Click 'Check Tx' Button Check @${call.from.username}</b>`, { reply_markup: markup, parse_mode: 'HTML' });
  49. bot.answerCallbackQuery(call.id, { text: "", show_alert: false });
  50. }

      

4.3 邀请

        邀请实际是通过在机器人链接后拼接命令,格式为:https://t.me/{机器人名}?start={邀请人id},这样当邀请人点击你的链接并使用start命令启动机器人时,则可以获取到链接后的邀请人Id,然后给邀请人发消息并发送代币奖励.实现代码如下:

  1. // 检查是否有邀请码
  2. if (checkCommandsParams(message, "start")) {
  3. const inviterUserId = getCommandsParams(message);
  4. const fromUserId = message.from?.id??0;
  5. //连续点击监测
  6. if (!passGameTime(fromUserId)) {
  7. bot.sendMessage(message.chat.id, "<b>Please do not send duplicate messages</b>", { parse_mode: 'HTML' });
  8. return;
  9. }
  10. dailyCommandTime[fromUserId] = Date.now();
  11. //自己邀请自己检测
  12. if (Number(inviterUserId) === fromUserId) {
  13. bot.sendMessage(message.chat.id, "<b>You cannot invite yourself!</b>", { parse_mode: 'HTML' });
  14. return;
  15. }
  16. //游戏钱包检测
  17. if (await notHasWallet(inviterUserId)) {
  18. bot.sendMessage(message.chat.id, "<b>The inviter has not created a wallet and cannot receive rewards</b>", { parse_mode: 'HTML' });
  19. return;
  20. }
  21. //已被邀请检测
  22. if (await hasShildUser(String(fromUserId))) {
  23. bot.sendMessage(message.chat.id, "<b>Invited users cannot receive rewards</b>", { parse_mode: 'HTML' });
  24. return;
  25. }
  26. //发送奖励
  27. const [amount, tx ] = await drawDailyCheck(String(SEND_USER_ID), inviterUserId);
  28. if (tx === "error") {
  29. bot.sendMessage(message.chat.id, "<b>send rewards Error!</b>", { parse_mode: 'HTML' });
  30. return;
  31. }
  32. if (tx == "error:account"){
  33. bot.sendMessage(message.chat.id, `<b>You must first send some BOGGY into the wallet before you can [DaliyCheck] and [invite] @${username}</b>`, { parse_mode: 'HTML' });
  34. return;
  35. }
  36. const markup = {
  37. inline_keyboard: [
  38. [
  39. { text: "Check Tx", url: `https://solscan.io/tx/${tx}` }
  40. ]
  41. ]
  42. };
  43. bot.sendMessage(message.chat.id, `<b>You have accepted the inviter's invitation and the reward ${amount} BOGGY has been sent to the inviter. Click 'Check Tx' Button Check @${message.from?.username}</b>`, { reply_markup: markup, parse_mode: 'HTML' });
  44. bot.sendMessage(inviterUserId, `<b>The Invited amount ${amount} BOGGY transfer end, Click 'Check Tx' Button Check</b>`, { reply_markup: markup, parse_mode: 'HTML' });
  45. addShildUser(String(fromUserId), inviterUserId);

4.4 WalletConnect连接

      用户输入/wclink命令后,则调用initWalletConnect进行配对,并发送连接请求,同时通过传入的approval监听用户的连接情况,实现代码如下:

  1. import Client, { SignClient } from "@walletconnect/sign-client";
  2. import TelegramBot from "node-telegram-bot-api";
  3. const metadata={
  4. name: 'BoggyGame',
  5. description: 'BoggyGame Bot',
  6. url: 'https://www.boggycoin.com',
  7. icons: [
  8. "https://i.postimg.cc/sftPCk3M/photo-2024-07-12-14-12-43.jpg"
  9. ]
  10. }
  11. const projectId="申请的ProjectId"
  12. let signClient: Client | null = null;
  13. async function getSignClient() {
  14. if (!signClient) {
  15. signClient = await SignClient.init({
  16. projectId: projectId, // 替换为你的项目ID
  17. metadata: metadata
  18. });
  19. }
  20. return signClient;
  21. }
  22. export async function initWalletConnect(onApproval: (approval: any,signClient:any,bot:any,message:any) => void,bot:TelegramBot,message:TelegramBot.Message):Promise<String|undefined> {
  23. const signClient = await getSignClient()
  24. // 创建会话并发送签名请求
  25. const {topic} = await signClient.core.pairing.create()
  26. const { uri,approval } = await signClient.connect({
  27. pairingTopic: topic,
  28. requiredNamespaces: {
  29. solana: {
  30. methods: [
  31. "solana_signTransaction",
  32. "solana_signMessage"
  33. ],
  34. chains: [
  35. "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
  36. ],
  37. events: []
  38. }
  39. }
  40. })
  41. // 调用回调函数处理 approval
  42. if (approval) {
  43. onApproval(approval,signClient,bot,message);
  44. }
  45. return uri;
  46. }

5.功能截图

AI图片生成

签到

邀请

获取链接:

奖励发放:


walletconnect连接



6.问题整理

        在集成node-telegram-bot-api组件时,出现网络问题,有时消息不回复,但是python版本运行良好.在Github上找到相关解决方法,给出的解释是要使用ipv4设置或者降低node版本,修改后代码运行良好,方法如下:

  1. const botToken = "123123123:testAAAAA";
  2. const telegramAPI = require("node-telegram-bot-api");
  3. const bot = new telegramAPI(config.botToken, { polling: true, request: {
  4. agentOptions: {
  5. keepAlive: true,
  6. //ipv4
  7. family: 4
  8. }
  9. }});
  10. bot.on("message", async function(msg) {
  11. await bot.sendMessage(msg.chat.id, "test");
  12. });

感谢您的关注和收藏!!!!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/933913?site
推荐阅读
相关标签
  

闽ICP备14008679号