protoncr / tourmaline

Simple Telegram bot library for Crystal
https://tourmaline.dev
MIT License
161 stars 39 forks source link

Don't work ENV["API_KEY"] in README example #31

Closed Mostik closed 4 years ago

Mostik commented 4 years ago

Hi! I tried to run example bot in README and I get unhandled exception.

require "tourmaline"

class EchoBot < Tourmaline::Client
  @[Command("echo")]
  def echo_command(ctx)
    ctx.message.reply(ctx.text)
  end
end

bot = EchoBot.new(ENV["5952279715:AAGEVsV3Y_t64zZ7QSndK..."])
bot.poll

Unhandled exception: Missing ENV key: "5952279715:AAGEVsV3Y_t64zZ7QSndK..." (KeyError)

Then I went to the site and took another example of the same code.

require "tourmaline"

class EchoBot < Tourmaline::Client
  @[Command("echo")]
  def echo_command(ctx)
    ctx.message.respond(ctx.text)
  end
end

bot = EchoBot.new("5952279715:AAGEVsV3Y_t64zZ7QSndK...")
bot.poll

And this code work! Is it a bug in my code or in a framework? The token was complete this one I came up with for an example...

bulgakke commented 4 years ago

API_KEY is the name of an environment variable (google if you don't know what that is). The example code presumes you've set up this variable to be equal to "your-api-key-here228"

Bot.new(key : String) accepts a String value and uses it as an API key to access Telegram. ENV["API_KEY"] is a Crystal way of accessing the value stored in the environment variable called API_KEY, read more here: https://crystal-lang.org/api/0.35.1/ENV.html . If you don't want to bother with it right now, you can just pass the key as a String (as in your working example) or assign it to a regular Crystal variable:

tg_key = "123385265:ahskdkdkxbbx"
bot = YourBot.new(tg_key)
bot.poll

Don't keep it as a permanent solution, if you plan on sharing the code anywhere outside of your local machine in any way.

I can't explain ways of setting env vars better than Google, so go there

Also, it's a bad practice to show your API keys (any keys, not just for TG) to someone online, even if you aren't going to do anything serious with it. You should revoke this one (at @BotFather).

watzon commented 4 years ago

Thanks @bulgakke. I'm going to mark this as a question and consider it closed.