Can I store bot state data on the involved telegra

2019-09-20 03:59发布

问题:

I'm trying to store a bit of data regarding the bot's conversation within a group (i.e. the bot manages kind of a text-based chat scape room and I want to save which "world" and "stage" the group is in at the time), and so I was wondering whether you can just store this little amount of data within the chat itself (instead of saving it on the bot server side*, which seems quite a lot of work for something that should be so simple).

So following this python zen philosophy, I'm trying to find a KISS way of storing that couple of values, maybe within the telegram chat itself, so that I don't need to manage any serious database on the server side in order to classify which chat things came from.

*I'm using telepot with webhook in a Flask web app.

回答1:

So... I just wanted to share that I found a deeply ridiculous but quite effective way of doing it (as long as you don't need to store private data in there, and with the condition that only the bot -and not the players- can mess with the chat's description).

Bots can check and change the chat's description via the commands bot.getChat("@group_id") and .setChatDescription("@group_id","New desc") so you actually can save there a string that contains all the values you need, and retrieve them later.

In the case exposed, I could save the current game level in the description, like "Level: 4", and retrieve it at any time by:

desc = bot.getChat("@my_game_chat")["description"]
level = desc[7:]

And in this case it works as a clue for the player too.

Using a similar approach you could save different stuff there at the same time, even maybe obscuring it a bit by just putting it as a string of numbers with no labels "01-21-5493"

desc = bot.getChat("@my_game_chat")["description"]
world, stage, score = desc.split('-')

Also if you work with fixed width numbers, you could even throw in there some random numbers in irrelevant places so as to confuse any possible gossip.

PS: bot.getChat() returns a structure like this (that's why we need ["description"]):

{
'id': -2424242424242, 
'title': 'Channel Name', 
'username': 'channelusername', 
'type': 'channel', 
'description': 'Pernils i tal'
}