[英]Simple Python Slackbot does not listen or respond to channel
I am getting started with the Slack API, so i just wanted to write a bot that listens into a channel and whenever someone says a keyword, it responds with an answer. 我开始使用Slack API,所以我只想编写一个侦听频道的漫游器,每当有人说出关键字时,它就会回答。 In this case, if someone says 'hello' it responds with 'world'.
在这种情况下,如果有人说“你好”,它将以“世界”回应。
Here is what I have done so far. 到目前为止,这是我所做的。 I registered for a Slack account.
我注册了一个Slack帐户。 I registered aa new bot at https://slack.com/apps/build >> Make a Custom Integration >> Something just for my team, gave it a name etc.
我在https://slack.com/apps/build上注册了一个新的bot >>进行自定义集成>>仅适用于我的团队的东西,并为其命名等。
Then i created a virtualenv and then wrote this script: 然后我创建了一个virtualenv,然后编写了这个脚本:
import time
from slackclient import SlackClient
BOT_TOKEN = "I PUT MY TOKEN HERE THAT I GOT FROM REGISTRATION"
CHANNEL_NAME = "general"
def main():
# Create the slackclient instance
sc = SlackClient(BOT_TOKEN)
# Connect to slack
if sc.rtm_connect():
# Send first message
sc.rtm_send_message(CHANNEL_NAME, "I'm the Hello World Bot")
while True:
# Read latest messages
for slack_message in sc.rtm_read():
message = slack_message.get("text")
user = slack_message.get("user")
if not message or not user:
continue
if "hello" in message:
sc.rtm_send_message(CHANNEL_NAME, "world")
else:
print("Couldn't connect to slack")
if __name__ == '__main__':
main()
When i run it, my command prompt is just blinking, nothing happens, not even the intro message in the channel. 当我运行它时,我的命令提示符只是闪烁,什么都没有发生,甚至没有频道中的介绍性消息。 So I have a few questions:
所以我有几个问题:
1) What is wrong, if anything, with my script? 1)我的脚本出了什么问题?
2) In my Slack, I can see the bot's name in the Direct Messages list, but when i go to the #general channel, I only have one user, me, and the bot is not there. 2)在我的Slack中,我可以在Direct Messages列表中看到该机器人的名称,但是当我进入#general频道时,我只有一个用户,而该机器人不在那儿。 How do i add it there?
如何在其中添加? When i click invite, it wants me to add people by email.
当我单击邀请时,它希望我通过电子邮件添加人员。
3) If I wanted it to listen to multiple channels, what would I have to change in the script? 3)如果我想让它收听多个频道,脚本中我将需要更改什么?
As @smarx said, you definitely need to invite your bot to the channel. 正如@smarx所说,您绝对需要邀请您的漫游器进入该频道。 And then I use the
chat.postMessage
method to do a call and response: 然后,我使用
chat.postMessage
方法进行呼叫和响应:
if re.search("hello", message):
self.client.api_call("chat.postMessage", as_user="true",
channel=CHANNEL_NAME, text="world")
I also have a pause in my script, so try something closer to: 我的脚本中也有一个停顿处,因此请尝试以下方法:
while True:
for slack_message in sc.rtm_read():
message = slack_message.get("text")
user = slack_message.get("user")
room = slack_message.get("channel")
if re.search("hello", message):
self.client.api_call("chat.postMessage", as_user="true",
channel=CHANNEL_NAME, text="world")
time.sleep(0.25)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.