thenewcoder
thenewcoder

Reputation: 61

Python Traceback: Key Error

I've been learning how to use Python and Slack for my class project. I'm particularly working on slack threads so I can direct message my entire class.

import os
from slackclient import SlackClient

slack_token = os.environ["xoxb-restofapitoken"]
sc = SlackClient(slack_token)

sc.api_call(
"chat.postMessage",
channel="#general",
text="Hello from Python! :tada:",
thread_ts="1476746830.000003",
reply_broadcast=True

)

When I run the code, the error below shows.

Traceback (most recent call last):
File "chat1.py", line 4, in <module>
slack_token = os.environ["xoxb-restofapitoken"]
File "/home/ubuntu/starterbot/lib/python2.7/UserDict.py", line 40, in __getitem__
  raise KeyError(key)
KeyError: 'xoxb-restofapitoken'

What am I doing wrong?

Upvotes: 1

Views: 5071

Answers (1)

mcgag
mcgag

Reputation: 355

I've met similar error before. There is nothing wrong with your code. However, kindly follow Slack's guideline when you are using test tokens , "pass tokens in as environment variables".

Change the code to:

import os
from slackclient import SlackClient

slack_token = os.environ["SLACK_BOT_TOKEN"]
sc = SlackClient(slack_token)

sc.api_call(
"chat.postMessage",
channel="#general",
text="Hello from Python! :tada:",
thread_ts="1476746830.000003",
reply_broadcast=True

)

Run it with:

SLACK_BOT_TOKEN="xoxb-restofapitoken" python myapp.py

and you should be good to go.

Upvotes: 2

Related Questions