当前位置: 首页 > news >正文

小试牛刀-Telebot区块链游戏机器人

目录

1.编写目的

2.实现功能

2.1 Wallet功能

2.2  游戏功能

2.3  提出功能

2.4  辅助功能

3.功能实现详解

3.1 wallet功能

3.2 游戏功能

3.3 提出功能

3.4 辅助功能

4.测试视频 


Welcome to Code Block's blog

本篇文章主要介绍了

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

1.编写目的

        本文章为记录自己开发基于区块链和Telebot实现的[石头、剪刀、布]游戏的过程,加深自己对区块链知识的理解和使用,加深对TeleBot依赖库的使用,同时希望可以帮助到有想实现相关功能的朋友.     

2.实现功能

2.1 Wallet功能

       用户可以通过/create命令命令创建游戏wallet,同时可以输入地址或扫码向该wallet发送一定数量的游戏代币,使用/wallet命令可以显示当前游戏wallet内的剩余代币数量。

2.2  游戏功能

        用户可以将bot机器人添加到公开群组,同时在群组内发送/game命令创建具有奖励随机结果的游戏,使用不同的人向群组内回复该游戏/pk进行对战,获取对战结果并向游戏wallet发送设定的奖励游戏代币,用户可以使用/del删除当前已创建游戏。

2.3  提出功能

        用户可以通过/bind命令绑定外部wallet并进行代币提出.

2.4  辅助功能

        用户可以输入/rules查看游戏规则,输入/help命令查看机器人命令及解释。

3.功能实现详解

3.1 wallet功能

        用户通过/create命令命令创建游戏wallet可以参考我的博客生成solana公私钥,/wallet显示wallet信息是通过solana.py根据保存的用户公钥查询.

def getBalance(publicKey:str):solana_client = Client(rpc_url)#公钥转换pubkey=Pubkey.from_string(publicKey)tokenPublicKey=Pubkey.from_string(BOGGY_TOKEN_MINT)#获取SOL余额sol_balance = solana_client.get_balance(pubkey)#获取SPL代币余额token_account=solana_client.get_token_accounts_by_owner_json_parsed(pubkey,TokenAccountOpts(mint=tokenPublicKey))if noTokenAccount(token_account):#不存在代币账户时,则余额为0token_balance=0.0else:token_account_json=token_account.value[0].account.to_json()token_balance=json.loads(token_account_json)['data']['parsed']['info']['tokenAmount']['uiAmount']sol_balance=(sol_balance.value/10**9)return sol_balance,token_balance

        同时为方便用户使用,这边会将用户公钥通过qrcode库转换为二维码供用户扫码,主要代码为:

import qrcode
from io import BytesIO
from PIL import Image
import qrcode.maindef generate_qr(data):# 生成普通二维码qr = qrcode.main.QRCode(version=1,box_size=10,border=4,)qr.add_data(data)qr.make(fit=True)qr_img = qr.make_image(fill_color="black", back_color="white")# 将二维码图片保存到 BytesIO 对象中img_io = BytesIO()qr_img.save(img_io, format='PNG')img_io.seek(0)return img_io

实现效果:

3.2 游戏功能

        游戏功能的设计思路是当用户在群组内输入/game时,根据(群组id+用户id+消息id)生成唯一的游戏id并通过json文件存储创建者生成的随机值信息.存储信息如下:

{"create_user_id": 5385955983,"create_username": "GameOfBoggy","create_select": 0,"pk_user_id": 2038830708,"pk_username": "USERT1223","pk_select": 1,"pk_select_hex": "4b32e3c83744655cd4ab5cc991a342c99f52c73fa83f2393a995d53baf7aeb42","amount": 20,"winner": "USERT1223","create_select_hex": "bd55d5aa6e461c63c811ff78bb00753c517eba47f086e563783a5e023ff342af","timestamp": 1721092512.869742,"create_drand_hex": "e3b4d8b6af061ddc40449d87c57c06d93de8fa73dff0055a07cc8dadb047dd1e","pk_drand_hex": "808391bb3761db7f5be8ba296e143154f043ecced8e7a693698c8490300fe34f"
}

这里的是使用本地secrets库和调用远程的drand随机数链生成两个hash值(create_drand_hex和create_select_hex为创建者游戏结果计算hash,pk_select_hex和pk_drand_hex为pk者游戏结果计算hash,这些结果面会保存到链上以保证游戏结果公平性和随机性.),这两个hash值转换为整数相加并对3取余获得随机结果,以保证游戏的随机性和不可预测性:

调用远程drand API:

def get_drand_randomness():# Drand API endpointurl = "https://api.drand.sh/52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971/public/latest"# Send request to Drandresponse = requests.get(url)if response.status_code == 200:# Parse the JSON responsedata = response.json()randomness = data['randomness']return randomnesselse:return secrets.token_hex()

计算游戏随机结果:

def get_random_hex_int():select_hex=secrets.token_hex()drand_hex=get_drand_randomness()hex_int = int(select_hex, 16)drand_int = int(drand_hex,16)select=(drand_int+hex_int)%3return select,select_hex,drand_hex

为保证游戏的美观性,这边使用图片+文字方式让机器人回复用户随机结果:

def random_game(bot,message,type,create_username):select,select_hex,drand_hex = get_random_hex_int()imgPath="./img/{}.png".format(img[select])msgText="<b>[{}] You random [{}]! @{}</b>".format(type,img[select],create_username)send_message=bot.send_photo(message.chat.id, open(imgPath, 'rb'), caption=msgText,parse_mode='HTML')return select,send_message,select_hex,drand_hex

游戏奖励发放给获胜者为代币转移操作,实现代码如下(这里的draw_data即为计算出结果的hash值,将其备注添加链上):

#向绑定账户发送代币
def drawTokenAccount(sender_public_key:str,privateKey:str,draw_public_key:str,tokenAmount,draw_data):solana_client = Client(rpc_url)#发送者sender_pubkey = Pubkey.from_string(sender_public_key)#接收者draw_pubkey = Pubkey.from_string(draw_public_key)#Token代币地址token_mint_address = Pubkey.from_string(BOGGY_TOKEN_MINT)#发送者keypairsender_keypair=Keypair.from_base58_string(privateKey)try:#spl_client客户端source_token_account=get_associated_token_address(sender_pubkey,token_mint_address)dest_token_account=get_associated_token_address(draw_pubkey,token_mint_address)#交易transfer_instruction = transfer_checked(TransferCheckedParams(program_id=TOKEN_PROGRAM_ID,source=source_token_account,mint=token_mint_address,dest=dest_token_account,owner=sender_pubkey,amount=int(float(tokenAmount) * 1000000000),decimals=9,))memo_instruction=create_memo(MemoParams(program_id=MEMO_PROGRAM_ID,signer=sender_pubkey,message=draw_data.encode('utf-8')))# #获取最新的区块hashrecent_blockhash_resp = solana_client.get_latest_blockhash()recent_blockhash=recent_blockhash_resp.value.blockhash# # 创建交易并添加转账指令transaction = Transaction()transaction.add(set_compute_unit_limit(200000))transaction.add(set_compute_unit_price(7500))transaction.add(transfer_instruction)transaction.add(memo_instruction)#设置最新区块hashtransaction.recent_blockhash=recent_blockhash#设置手续费支付地址为发送者transaction.fee_payer=sender_pubkey#签名transaction.sign(sender_keypair)#发送交易response = solana_client.send_raw_transaction(transaction.serialize())#打印交易return response.valueexcept Exception as e:print(f"Exception occurred: {str(e)}")return "error"

实现效果:

/game 20 即创建了一个奖励为20代币的游戏,这里随机的是[剪刀]

/pk pk者出了[布],所以创建者获得了奖励.

我们可以点击按钮在链上查看奖励内容.

可以看到这里包含了一个转移代币操作,是从pk者转移到创建者中的,同时包含了生成随机结果的hash值以保证游戏的公开和公平性。 

3.3 提出功能

        用户输入/bind 绑定自己的链上地址后,提出功能即为代币转移操作,主要实现代码如下,这边直接根据用户的ID查到用户的创建的游戏wallet公钥私钥并进行转移:

def drawTokenFromUserId(send_user_id,draw_user_id,gameId,draw_data):publicKey,privateKey=get_account(send_user_id)drawPublicKey=getPublicKey(draw_user_id)amount=get_game_amount(gameId)tx=drawTokenAccount(publicKey,privateKey,drawPublicKey,amount,draw_data)return amount,tx

3.4 辅助功能

        辅助功能即为telebot消息的回复,实现代码如下:

/rules:

from telebot import types
def handle_rules(bot, message):# 处理 /start 命令markup = types.InlineKeyboardMarkup()item1 = types.InlineKeyboardButton("BOGGY GROUP",url="https://t.me/BoggyCoin")markup.add(item1)welcome_message=("<b>""1.Before starting the game, you need to create(/create) a game wallet and transfer a small amount of sol and BOGGY tokens inward\n\n""2.You can send '/game [amount]' create a game(default amount:500),and the Pker reply /pk with [GAME](need enough sol and BOGGY)\n\n""3.Waiting for the results, the winner will receive the bonus set by the game creator\n\n""4.The [Scissors] will win [Paper],[Parer] will win [Rock],[Rock] will win [Scissors]\n\n""5.You Can at /wallet,draw you all token in you bind wallet,you can send '/bind [address]' bind you wallet\n\n""[Create With #BOGGY]""</b>")bot.send_photo(message.chat.id,open("./img/rules.jpeg","rb"),welcome_message,parse_mode='HTML',reply_markup=markup)
def register_handlers(bot):bot.message_handler(commands=['rules'])(lambda message: handle_rules(bot, message))

/help:

from telebot import types
def handle_help(bot, message):markup = types.InlineKeyboardMarkup()item1 = types.InlineKeyboardButton("BOGGY GROUP",url="https://t.me/BoggyCoin")markup.add(item1)help_text = ("<b>Welcome!</b>\n" "<b>Here are the available commands:</b>\n""<b>[/create]         Create you game wallet [DM*]</b>\n""<b>[/bind]           Bind you draw wallet [DM*]</b> \n""<b>[/wallet]         Show you wallet Info and Draw [DM*]</b>\n\n""<b>[/game]           Create Game with amount</b>\n""<b>[/pk]             Reply the Game Message and Pk it</b>\n""<b>[/rules]          View more detailed game rules</b>\n\n""<b>The [DM*] need DM Bot</b>")bot.send_photo(message.chat.id,open("./img/help.jpeg","rb"),help_text, parse_mode='HTML',reply_markup=markup)def register_handlers(bot):bot.message_handler(commands=['help'])(lambda message: handle_help(bot, message))

4.测试视频 

video_2024-07-16_11-48-41

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

 

 

http://www.lryc.cn/news/403103.html

相关文章:

  • 使用github actions构建多平台electron应用
  • java通过pdf-box插件完成对pdf文件中图片/文字的替换
  • 鸿蒙 next 5.0 版本页面跳转传参 接受参数 ,,接受的时候 要先定义接受参数的类型, 代码可以直接CV使用 [教程]
  • 【electron6】浏览器实时播放PCM数据
  • 嵌入式C/C++、FreeRTOS、STM32F407VGT6和TCP:智能家居安防系统的全流程介绍(代码示例)
  • 【Django】django自带后台管理系统样式错乱,uwsgi启动css格式消失的问题
  • 解决npm install(‘proxy‘ config is set properly. See: ‘npm help config‘)失败问题
  • 汽车及零部件研发项目管理系统:一汽东机工选择奥博思 PowerProject 提升研发项目管理效率
  • Keil开发IDE
  • 数据结构与算法05堆|建堆|Top-k问题
  • 【精简版】jQuery 中的 Ajax 详解
  • win10删除鼠标右键选项
  • 分层评估的艺术:sklearn中的策略与实践
  • 排序系列 之 快速排序
  • 【银河麒麟服务器操作系统】java进程oom现象分析及处理建议
  • Redis的AOF持久化策略(AOF的工作流程、AOF的重写流程,操作演示、注意事项等)
  • 共享模型之无锁
  • 下载安装VSCode并添加插件作为仓颉编程入门编辑器
  • 解决:Linux上SVN 1.12版本以上无法直接存储明文密码
  • Mongodb多键索引中索引边界的混合
  • 如何利用windows本机调用Linux服务器,以及如何调用jupyter界面远程操控
  • 如何定位Milvus性能瓶颈并优化
  • 阿里云服务器 篇三:提交搜索引擎收录
  • powe bi界面认识及矩阵表基本操作 - 1
  • SpringBoot 项目 pom.xml 中 设置 Docker Maven 插件
  • k8s二次开发-kubebuiler一键式生成deployment,svc,ingress
  • Flutter 状态管理新境界:多Provider并行驱动UI
  • 标识符和关键字的区别是什么,常用的关键字有哪些?自增自减运算符,移位运算符continue、break、return的区别是什么?
  • 在VS Code上搭建Vue项目教程(Vue-cli 脚手架)
  • AGI 之 【Hugging Face】 的【零样本和少样本学习】之三 [无标注数据] 的简单整理