PaulSonOfLars / gotgbot

Autogenerated Go wrapper for the telegram API. Inspired by the python-telegram-bot library.
MIT License
510 stars 118 forks source link

User data is not kept in the context between updates #86

Closed vlipovetskii closed 1 year ago

vlipovetskii commented 1 year ago

Description of the problem / feature request

d.ProcessUpdate(b, &upd, nil) is always invoked with data = nil, and thus it effectively clears up the user data after each update.

func (d *Dispatcher) ProcessRawUpdate(b *gotgbot.Bot, r json.RawMessage) error {
    var upd gotgbot.Update
    if err := json.Unmarshal(r, &upd); err != nil {
        return fmt.Errorf("failed to unmarshal update: %w", err)
    }

    return d.ProcessUpdate(b, &upd, nil)
}

// ProcessUpdate iterates over the list of groups to execute the matching handlers.
func (d *Dispatcher) ProcessUpdate(b *gotgbot.Bot, update *gotgbot.Update, data map[string]interface{}) (err error) {
    ctx := NewContext(update, data)
PaulSonOfLars commented 1 year ago

Hi, thanks for raising an issue!

However, this is intentional - the data is not "user data", it is intended to be update-local data. You can store whatever data you need in it for the duration of the update. So yes, when the library starts to process an update, the value will always be nil.

Update local data can be useful to avoid recomputing things across different handlers. For example, you might want to avoid repeated admin checks for a single update, so once you've done an admin check in one handler, you can reuse that result in a later handler by storing it in the update data. Does that make sense?

If you're looking to store user data, I recommend using a persistent storage such as a database, to ensure that no data is lost across restarts

vlipovetskii commented 1 year ago

Thank you for the detailed explanation! I have chosen your framework, because it Heavily inspired by the python-telegram-bot library,. I used python-telegram-bot heavily and ptb supports Storing bot, user and chat related data. By analogy I have decided, that data is like ptb "user_data". I will follow your advice and create own user data storage. Please close the issue.

P.S. Now Data is not commented in the code. `type Context struct { *gotgbot.Update Data map[string]interface{}

// EffectiveMessage is the message which triggered the update, if possible
EffectiveMessage *gotgbot.Message`

Could you add the comment with your explanation to help other users of ptb avoiding confusion.

PaulSonOfLars commented 1 year ago

I've added a comment to explain this in #88.

Let me know if you'd like me to add anything else!