Slack Bot | Get datepicker value - python

I'm trying to create my first slack bot with python.
I need your help to explain how I can get the value of the datepicker.
This is my code :
import os
from slack import WebClient
from slack.errors import SlackApiError
import time
client = WebClient(token=os.environ['SLACK_KEY'])
message = "Hey ! Pourrais-tu saisir la date de tes congés ce mois-ci ?"
attachments = [{
"blocks": [
{
"type": "actions",
"elements": [
{
"type": "datepicker",
"initial_date": "1990-04-28",
"placeholder": {
"type": "plain_text",
"text": "Select a date",
}
},
{
"type": "datepicker",
"initial_date": "1990-04-28",
"placeholder": {
"type": "plain_text",
"text": "Select a date",
}
}
]
}
]
}]
def list_users():
users_call = client.api_call("users.list")
if users_call.get('ok'):
return users_call['members']
return None
def send_message(userid):
response = client.chat_postMessage(channel=userid, text=message, username='groupadamin', attachments=attachments)
if __name__ == '__main__':
users = list_users()
if users:
for u in users:
send_message(u['id'])
print("Success!")
My bot sends a private message to all users of the slack. I want to get every one of their answers of the datepicker.
If you want more details, ask me.

In general, you need to be listening to the action.
When the use clicks the datetimepicker, a so-called interaction-payload will be sent to your python slackbot.
That payload is documented here https://api.slack.com/reference/interaction-payloads/block-actions ; you can see you can get the picked date's value by accessing actions.value.
In particular for your use case, given your code sample, it seems you've just built a script that can send messages. This will not allow you to listen to actions. You need rather a python service (an API) that can send as well as receive messages.
For this, I suggest having a look at bolt which is a slack maintained library that will take care of a lot of the heavy lifting for you. Specifically, regarding actions you can check https://slack.dev/bolt-python/concepts#action-listening

Related

Telegram Webhook doesn't send text from Group Chats

I am running a Telegram bot using Webhooks that queries an AWS Lambda function. In a private conversation with just the bot, it functions as expected. In group chats however, the bot fails to respond. In particular, when receiving updates from a group, the Message object is missing the text field (i.e. there is no text associated with messages from group chats).
Here is what I have tried:
Setting privacy mode to disabled (such that the bot can access all messages in groups)
Giving the bot admin privileges
Removing and adding the bot after doing the above
Deleting and recreating a whole new bot after doing the above
Deleting and setting a webhook
Here is the lambda code (it simply echos back whatever it receives):
import requests
import json
def lambda_handler(event, context):
# get the request body from API gateway
body = json.loads(event['body'])
token = 'my secret token'
URL = "https://api.telegram.org/bot{}/".format(token)
chat_id = body['message']['chat']['id']
# This if statement is triggered for EVERY group chat message the bot receives
# which is the error I'm trying to debug
if 'text' not in body['message']:
return { 'statusCode': 500 }
# this only works for direct messages
message = body['message']['text']
send_url = URL + "sendMessage?text={}&chat_id={}".format(message, chat_id)
requests.get(send_url)
response = {
"statusCode": 200
};
return response
Here is what the Message object looks like when received from a group chat (notice that it doesn't have a text field:
{
"message_id":27,
"from":{
"id":id_number,
"is_bot":False,
"first_name":"Jafer",
"last_name":"",
"username":"username",
"language_code":"en"
},
"chat":{
"id":-id_number,
"title":"test",
"type":"group",
"all_members_are_administrators":True
},
"date":1603138229,
"group_chat_created":True
}
Here are some of the resources on stackoverflow that I've already looked at:
Allow bot to access Telegram Group messages
python telegram bot(Telepot) group chat
Since I'm trying to run the bot in a serverless environment, I cannot use a polling mechanism as suggested here: Telegram Bot - how to get a group chat id?
I would very much appreciate some help understanding why my bot struggles with group chats! Thank you!
Your dumped response has "group_chat_created":True and it is a service message which normally doesn't have any text. This messages is created when a group is created (the first message of the group).
Docs says,
Field
Type
Description
group_chat_created
True
Optional. Service message: the group has been created
Your bot only receives this type of message if you create the group by adding the bot as a member first (i.e. when the bot is a member of the group when it is created.) Now, by default bot will not read the text messages, so, you can promote the bot as an admin to read the text messages.
As an example, if I create a group with a bot,
{
"update_id": 989846...,
"message": {
"message_id": 15,
"from": {
"id": 1521565...,
"is_bot": false,
"first_name": "me",
"username": "abc...",
"language_code": "en"
},
"chat": {
"id": -560877...,
"title": "MeAndMyBot...",
"type": "group",
"all_members_are_administrators": true
},
"date": 1614624584,
"group_chat_created": true
}
}
And you can see that,
Now give the appropriate permissions (e.g.: Admin privileges) to access text messages,
Then we can get updates like,
{
"update_id": 989846...,
"message": {
"message_id": 16,
"from": {
"id": 1521565...,
"is_bot": false,
"first_name": "me",
"username": "abc...",
"language_code": "en"
},
"chat": {
"id": -560877...,
"title": "MeAndMyBot...",
"type": "group",
"all_members_are_administrators": true
},
"date": 1614625333,
"text": "Hello there"
}
}

How do I pull new employee information from DocuSign through API?

Is it possible to pull the new employee’s personal information who gets hired every day from DocuSign through API? I'm trying to find a way to automate the process of user account creation process from DocuSign to Active Directory by avoiding CSV file. New to this, any input might be useful?
There are two parts to this endeavor.
The first, is not related to DocuSign. You need to get an event fired everytime a new contact is added to AD and be able to process this request. I assume you have a way to do that.
Then, the second part is using our REST API to add a new user.
Make a POST request to:
POST /v2.1/accounts/{accountId}/users
You pass this information in the request body:
{
"newUsers": [
{
"userName": "Claire Horace",
"email": "claire#example.com.com"
},
{
"userName": "Tal Mason",
"email": "tal#example.com.com",
"userSettings": [
{
"name": "canSendEnvelope",
"value": "true"
},
{
"name": "locale",
"value": "fr"
}
]
}
]
}

Slack API: Can't send attachments

I'm trying to send an attachment using Slack's Python Client but whenever I do I fail. I tried sending it with the Tester too but it still didn't work. Either I get {"ok": false,"error": "no_text"} or if I have the text property only the text is going to be sent. This is how I do it. I searched too but didn't found anything.
attachment = json.dumps([{"attachments": [{"fallback": "Reddit Message","color": "#448aff","pretext":"You've got a new Message!","author_name": "Reddit","author_link": "https://reddit.com","author_icon": "imageurl","title": "Reddit Message","title_link": "https://reddit.com/message/inbox","text": "This is what I know about it.","fields": [{"title": "Author:","value": str(item.author),"short": "true"},{"title": "Subject: ","value": str(item.subject),"short": "true"},{"title": "Message:","value": str(item.body),"short": "false"}],"footer": "Reddit API","footer_icon": "anotherimageurl"}]})
sc.api_call("chat.postMessage",channel="U64KWRJAU",attachments=attachment,as_user=True)
Help would be appreciated. This should make sense but I don't get it why it doesn't work
From your reference, you need to pass attachment as a list. You won't need to have the attachments key in a dict containing the list.
attachment = json.dumps([
{
"fallback": "Reddit Message",
"color": "#448aff",
"pretext":"You've got a new Message!",
"author_name": "Reddit",
"author_link": "https://reddit.com",
....
}
])
sc.api_call(
"chat.postMessage", channel="U64KWRJAU",
attachments=attachment, as_user=True)
I met the same issue and found the solution.
The problem is that if only attachments field is added into the payload, it will report no_text error. But if text field is added, slack message will only show the text content.
The solution:
When we want to display attachments, we need to add a basic blocks field instead of text field. Something like
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "bar"
}
}
],
"attachments": [
{
"color": "#FF0000",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "foo"
}
}
]
}
]
}
If putting the above payload into the Slack build kit, it will be a misleading. That's also why I stuck with the issue.
I would recommend to use chat.postMessage test to debug the payload. It will work like a charm.
https://stackoverflow.com/a/72036841/3409400

Adding attachment to Slackbot

I'm trying to add an attachment to a slack message via their API. I'm using the python wrapper they recommend. I can send and receive basic messages but when I try to add an attachment in the form of 2 buttons it fails. I have made a slack app and linked the bot as they state in their API. I've carefully reviewed the API and cannot figure out what is going on.
def process_message(message, channel):
intro_msg = json.loads('{
"text": "What would you like to do?",
"attachments": [
{
"text": "Choose an action",
"fallback": "You are unable to choose an option",
"callback_id": "lunch_intro",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "enroll",
"text": "Enroll",
"type": "button",
"value": "enroll"
},
{
"name": "leave",
"text": "Leave",
"type": "button",
"value": "leave"
}
]
}
]
}')
r = sc.api_call("chat.postMessage", channel=channel, attachments=intro_msg)
The response is only {u'ok': False, u'error': u'no_text'}
I figured it out.
The python wrapper separates out the payload.
intro_msg = json.dumps([{"text":"Choose an action","fallback":"You are unable to choose an option","callback_id":"lunch_intro","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"enroll","text":"Enroll","type":"button","value":"enroll"},{"name":"leave","text":"Leave","type":"button","value":"leave"}]}])
sc.api_call("chat.postMessage", channel=channel, text="What would you like to do?", attachments=intro_msg, as_user=True)
My payload was all in attachments since that is how they format it in their API docs. The attachments needs to just be the array after the attachments key.
I guess the basic simple example works.
Example:
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
sc.api_call(
"chat.postMessage",
channel="#python",
text="Hello from Python! :tada:"
)
According to https://api.slack.com/methods/chat.postMessage and https://api.slack.com/docs/message-buttons#readying_your_application_for_message_buttons the attachments has to be an array. How about sending it as array:
json.loads('[{"text":"What would you like to do?","attachments":[{"text":"Choose an action","fallback":"You are unable to choose an option","callback_id":"lunch_intro","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"enroll","text":"Enroll","type":"button","value":"enroll"},{"name":"leave","text":"Leave","type":"button","value":"leave"}]}]}]')
As there is no further magic involved but the requests module https://github.com/slackapi/python-slackclient/blob/ddf9d8f5803040f0397d68439d3217d1e1340d0a/slackclient/_slackrequest.py I'd give it a try with the sending as array.

Python facebook-sdk: retrieving names of users who posted a message on a page

I want to use the Python facebook-sdk library to retrieve the names of the persons who posted a message on a Facebook page I created.
This is an example, returned by the Graph API explorer:
{
"feed": {
"data": [
{
"from": {
"name": "Ralph Crützen",
"id": "440590514975673"
},
"message": "Nog een test.",
"created_time": "2015-10-17T19:33:30+0000",
"id": "649463214822976_649745285127205"
},
{
"from": {
"name": "Ralph Crützen",
"id": "440590514975673"
},
"message": "Testing!",
"created_time": "2015-10-16T20:44:17+0000",
"id": "649463214822976_649492455153388"
},
... etc ...
But when I use the following Python code...
graph = facebook.GraphAPI(page_access_token)
profile = graph.get_object('tinkerlicht')
posts = graph.get_connections(profile['id'], 'feed')
print(posts['data'][0]['message'])
print(posts['data'][0]['from']['name'])
...only the message value is printed. Printing the name of the person who posted the message gives the error:
print(posts['data'][0]['from']['name'])
KeyError: 'from'
At first, I thought that I needed the read_page_mailboxes permission. To use this permission, it has to be approved by Facebook, so I submitted a request. But Facebook replied:
"You don't need any additional permissions to post to Pages or blogs that you administer. You only need to submit your app for review if your app will use a public-facing login."
So what exactly is the reason I can't retrieve the from data from the messages feed? (While reading it from the Graph API explorer works fine...)
Btw, I'm using a page access token which never expires. I generated this token the way it's described here.

Categories