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?
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.
Related
I'm attempting to start working with building chat bot within python. I would really want to start programming one from scratch. I'm starting with the ChatterBot module to learn how it works. I have pip installed all modules but I'm still having trouble with 'ChatterBotCorpusTrainer'Im getting a missing error. I run python 3.7 and I have the updated ChatBot module.
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
import os
bot= ChatBot('Bot')
trainer = ChatterBotCorpusTrainer(bot)
corpus_path = '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/chatterbot_corpus/data/english'
for file in os.listdir(corpus_path):
trainer.train(corpus_path + file)
conversation = [
"Hello",
"Hi there!",
"How are you doing?",
"I'm doing great.",
"That is good to hear",
"Thank you.",
"You're welcome."
]
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')
response = chatbot.get_response("Good morning!")
print(response)
this is the error I'm getting
/Users/singlefawn/Desktop/Our Realm/1997/Programs/random gallery/venv/lib/python3.7/site-packages/chatterbot/storage/jsonfile.py:26: UnsuitableForProductionWarning: The JsonFileStorageAdapter is not recommended for production environments.
self.UnsuitableForProductionWarning
Traceback (most recent call last):
File "/Users/singlefawn/Desktop/Our Realm/1997/Programs/random gallery/chat_1_1.py", line 6, in <module>
trainer = ChatterBotCorpusTrainer(bot)
File "/Users/singlefawn/Desktop/Our Realm/1997/Programs/random gallery/venv/lib/python3.7/site-packages/chatterbot/trainers.py", line 101, in __init__
from .corpus import Corpus
File "/Users/singlefawn/Desktop/Our Realm/1997/Programs/random gallery/venv/lib/python3.7/site-packages/chatterbot/corpus/__init__.py", line 6, in <module>
from chatterbot_corpus import Corpus
ImportError: cannot import name 'Corpus' from 'chatterbot_corpus' (/Users/singlefawn/Desktop/Our Realm/1997/Programs/random gallery/venv/lib/python3.7/site-packages/chatterbot_corpus/__init__.py)
You need to specify the module (chatterbot.trainers). You have 2 options:
1
from chatterbot import trainers
2
trainer = chatterbot.trainers.ChatterBotCorpusTrainer
I am trying to move data (a dint specifically but my example is a BOOL) from the plc to python to be used as a variable to display a picture. The issue is, if I use pycomm, I am getting an error in Windows Powershell. I feel this is a very simple error from a basic python mistake rather than a pycomm issue but I am not informed enough to tell.
SysInfo:
configparser==3.5.0
cpppo==3.9.7
greenery==2.1
ipaddress==1.0.18
pycomm==1.0.8
pyreadline==2.1
pytz==2017.2
python==2.7.13
Code I am using:
from pycomm.ab_comm.clx import Driver as ClxDriver
import logging
if __name__ == '__main__':
c = ClxDriver()
if c.open('IPADDRESSHERE'):
print(c.read_tag(['new_Bool']))
c.close()
Which is just a stripped down version of one of the examples on github https://github.com/ruscito/pycomm
This is the result from running powershell:
PS C:\Users\Tom\Documents\PythonProjects> python pycomm2.py
Traceback (most recent call last):
File "pycomm2.py", line 10, in
print(c.read_tag(['new_Bool']))
File "C:\Python27\lib\site-packages\pycomm\ab_comm\clx.py", line 359, in read_tag
self.logger.warning(self._status)
AttributeError: 'Driver' object has no attribute 'logger'
PS C:\Users\Tom\Documents\PythonProjects>
I have looked for this AttributeError and tried to find a solution, but I think the solutions I have found are over my head. If I have failed to provide some details in order for this question to make sense please let me know.
Edit:
from pycomm.ab_comm.clx import Driver as ClxDriver
import logging
if __name__ == '__main__':
logging.basicConfig(
filename="ClxDriver.log",
format="%(levelname)-10s %(asctime)s %(message)s",
level=logging.DEBUG
)
c = ClxDriver()
if c.open('IPADRESSHERE'):
print(c.read_tag(['new_Bool']))
c.close()
Yields the same attribute error.
PS C:\Users\Tom\Documents\PythonProjects> python pycommtest.py
Traceback (most recent call last):
File "pycommtest.py", line 15, in
print(c.read_tag(['new_Bool']))
File "C:\Python27\lib\site-packages\pycomm\ab_comm\clx.py", line 359, in read_tag
self.logger.warning(self._status)
AttributeError: 'Driver' object has no attribute 'logger'
PS C:\Users\Tom\Documents\PythonProjects>
I was able to read a value, but not with pycomm. Using CPPPO, I was able to continuously update a variable as needed. This may not answer the question of what was wrong with my old code, but it is my work around in case someone from the future has to do the same thing. Credit to user Liverpool_chris and the abyss of Reddit.
https://www.reddit.com/r/PLC/comments/5x3y5z/python_cpppo_library_writing_to_tag_in_plc/
from cpppo.server.enip.get_attribute import proxy_simple
import time
host = "IPHERE"
while True:
x, = proxy_simple(host).read(( "CPID"))
print x
time.sleep(5)
I am trying to generate a list of product/vendor IDs with Pyusb and I am having trouble. I found a suggestion online from orangecoat.
import sys
import usb.core
import usb.util
dev = usb.core.find(find_all=True)
if dev is None:
raise ValueError('Device not found')
cfg = dev.get_active_configuration()
Python gives the following error though:
Traceback (most recent call last):
File "C:/Python27/usbfinddevices.py", line 10, in <module>
cfg = dev.get_active_configuration()
AttributeError: 'generator' object has no attribute 'get_active_configuration'
Could someone help me understand why I am getting this error?
Thank you
You're almost there, but you need to iterate through your dev object which is a generator.
dev = usb.core.find(find_all=True)
for d in dev:
print usb.util.get_string(d,128,d.iManufacturer)
print usb.util.get_string(d,128,d.iProduct)
print (d.idProduct,d.idVendor)
Save this script
test.py
import usb.core
import usb.util
dev = usb.core.find(find_all=True)
# get next item from the generator
d = dev.next()
print d.get_active_configuration()
then, run this
sudo python test.py
On Windows with Python 3 you need to change line d = dev.next() to d = next(dev) (as pointed out in the comments by #gabin)
I am using the following code to sign in to twitter:
import simplejson
import twitter
import oauth
import oauthtwitter
from oauthtwitter import OAuthApi
class OauthRequest():
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token'
def GetRequest(self):
vOauthApi = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET)
self.mOauthRequestToken = vOauthApi.getRequestToken(self.REQUEST_TOKEN_URL)
self.mOauthRequestUrl = vOauthApi.getAuthorizationURL(self.mOauthRequestToken)
However, I receive the following error message:
Traceback (most recent call last):
File "C:\Python33\twitter.py", line 4, in <module>
import oauthtwitter
File "C:\Python33\lib\site-packages\oauthtwitter.py", line 17, in <module>
from twitter import Api, User
ImportError: cannot import name Api
I have installed PIP and downloaded the 'oauth', 'oauthtwitter' and 'twitter' modules using it. I am running Windows Vista and Python 3.3. As far as I can tell in my 'Lib' folder the files are there for oauthtwitter.
I'm noy sure exactly what is going wrong here?
Thanks
I have installed pysnmp-4.x.I am getting following error during running a SNMP program.
I am using pysnmpSE 3.5.2 now but getting same error. I found that pysnmpSE doesn't hav v4 module. I was suggested that following error should resolved if pySNMP SE 3.x is used.
Traceback (most recent call last):
File "C:\Documents and Settings\ggne0622\Desktop\Python\google-python-exercises\babynames\SimpleAgent.py", line 18, in <module>
from twistedsnmp import agent, agentprotocol, bisectoidstore
File "C:\Python27\Lib\site-packages\twistedsnmp\agent.py", line 4, in <module>
from twistedsnmp import datatypes
File "C:\Python27\Lib\site-packages\twistedsnmp\datatypes.py", line 7, in <module>
from twistedsnmp.pysnmpproto import v2c,v1
File "C:\Python27\Lib\site-packages\twistedsnmp\pysnmpproto.py", line 13, in <module>
from pysnmp.v4.proto.omni import v2c,v1, error, rfc1157, rfc1905
ImportError: No module named v4.proto.omni
Code:
#!/usr/bin/env python
from twisted.internet.iocpreactor import reactor
from twisted.internet import error as twisted_error
from twistedsnmp import agent, agentprotocol, bisectoidstore
#from twisted.internet import interfaces
try:
from twistedsnmp import bsdoidstore
except ImportError:
import warnings
warnings.warn( """No BSDDB OID Storage available for testing""" )
bsdoidstore = None
def createAgent( oids ):
ports = [161]+range(20000,25000)
for port in ports:
try:
`agentObject = reactor.IOCPReactor.listenUDP(port,` `agentprotocol.AgentProtocol(snmpVersion = 'v2c',agent = agent.Agent(dataStore =` `bisectoidstore.BisectOIDStore(OIDs = oids,),),),)`
`except twisted_error.CannotListenError:`
`pass`
`else:`
`return agentObject, port`
testingOIDs = {
'.1.3.6.1.2.1.1.1.0': 'Some tool out in the field',
'.1.3.6.1.2.1.1.2.0': '.1.3.6.1.4.1.88.3.1',
'.1.3.6.1.2.1.1.3.0': 558566090,
'.1.3.6.1.2.1.1.4.0': "support#somewhere.ca",
'.1.3.6.1.2.1.1.5.0': "NameOfSystem",
'.1.3.6.1.2.1.1.6.0': "SomeHeadEnd, West Hinterlands, Canada",
}
def main(oids=testingOIDs):
agent, port = createAgent( oids )
if __name__ == "__main__":
reactor.IOCPReactor.callWhenRunning( main )
reactor.IOCPReactor.run()
TwistedSNMP does not seem to be designed to work with PySNMP 4.x. Thus you should either use PySNMP 3.x / PySNMP SE or switch to PySNMP 4.x which has its own Twisted binding.