Sendbee公共API的Python客户端SDK

sendbee-api的Python项目详细描述


Sendbee Python API客户端


                .' '.            __
       .        .   .           (__\_
        .         .         . -{{_(|8)
          ' .  . ' ' .  . '     (__/

PyPI versionBuild Status

GitHub issuesGitHub closed issuesGitHub closed pull requests

PyPI - Python VersionGitHubGitHub last commit

目录

联系人

联系人标签

联系人字段

对话

团队 自动化

麦克风

Installation

^{pr2}$

^{EHA4}
fromsendbee_apiimportSendbeeApiapi=SendbeeApi('__your_api_key_here__','__your_secret_key_here__')

联系人

Fetch contacts

contacts=api.contacts([tags=['...',...]],[status='subscribed|unsubscribed'],[search_query='...'],[page=...])forcontactincontacts:contact.idcontact.statuscontact.foldercontact.created_atcontact.namecontact.phonefortagincontact.tags:tag.idtag.namefornoteincontact.notes:note.valueforcontact_fieldincontact.contact_fields:contact_field.keycontact_field.value

Subscribe contact

contact=api.subscribe_contact(phone='+...',# this is mandatory the most important information# about the subscribing contact[tags=['...',...]],# tag new contact# if tag doesn't exist, it will be created[name='...'],[notes=[...]],# write notes about your new subscriber[contact_fields={'__field_name__':'__field_value__',...}],# fill contact fields with your data (value part)# contact fields must be pre-created in Sendbee Dashboard# any non-existent field will be ignored [block_notifications=[True|False]],# prevent sending browser push notification and email # notification to agents, when new contact subscribes# (default is True) [block_automation=[True|False]]# prevent sending automated template messages to newly# subscribed contact (if any is set in Sendbee Dashboard) # (default is True) )contact.idcontact.statuscontact.foldercontact.created_atcontact.namecontact.phonefortagincontact.tags:tag.idtag.namefornoteincontact.notes:note.valueforcontact_fieldincontact.contact_fields:contact_field.keycontact_field.value

Update contact

contact=api.update_contact(id='...',# contact is identified with ID[phone='+...'],# this is the most important information # about the subscribing contact[tags=['...',...]],# tag new contact# if tag doesn't exist, it will be created[name='...'],[notes=[...]],# write notes about your new subscriber# if there are notes already saved for this contact# new notes will be appended[contact_fields={'__field_name__':'__field_value__',...}],# fill contact fields with your data (value part)# contact fields must be pre-created in Sendbee Dashboard# any non-existent field will be ignored # if there are fields already filled with data for this contact# it will be overwritten with new data )contact.idcontact.statuscontact.foldercontact.created_atcontact.namecontact.phonefortagincontact.tags:tag.idtag.namefornoteincontact.notes:note.valueforcontact_fieldincontact.contact_fields:contact_field.keycontact_field.value

联系人标签

Fetch contact tags

tags=api.tags([name='...'],[page=...])fortagintags:tag.idtag.name

Create contact tag

tag=api.create_tag(name='...')tag.idtag.name

Update contact tag

tag=api.update_tag(id='...',name='...')tag.idtag.name

Delete contact tag

response=api.delete_tag(id='...')response.message

联系人字段

Fetch contact fields

contact_fields=api.contact_fields([search_query='...'],[page=...])forcontact_fieldincontact_fields:contact_field.namecontact_field.typeifcontact_field.type=='list':contact_field.options

Create contact field

如果联系人字段类型是列表,则需要发送列表选项。
List options是选项名称的列表:['option1', 'option2', ...]

contact_field=api.create_contact_field(name='...',type='text|number|list|date|boolean',[options=['...'....]]# if contact field type is list)contact_field.idcontact_field.namecontact_field.typeifcontact_field.type=='list':contact_field.options

Update contact field

如果联系人字段类型是列表,则需要发送列表选项。
List options是选项名称的列表:['option1', 'option2', ...]

contact_field=api.update_contact_field(id='...',[name='...'],[type='text|number|list|date|boolean'],[options=['...'....]]# if contact field type is list)contact_field.idcontact_field.namecontact_field.typeifcontact_field.type=='list':contact_field.options

Delete contact field

response=api.delete_contact_field(id='...')response.message

对话

Fetch conversations

conversations=api.conversations([folder='open|done|spam|notified'],[search_query='...'],[page=...])forconversationinconversations:conversation.idconversation.folderconversation.chatbot_activeconversation.platformconversation.created_atconversation.contact.idconversation.contact.nameconversation.contact.phoneconversation.last_message.directionconversation.last_message.statusconversation.last_message.inbound_sent_atconversation.last_message.outbound_sent_at

Fetch conversation messages

messages=api.messages(conversation_id='...',[page=...])formessageinmessages:message.bodymessage.media_typemessage.media_urlmessage.statusmessage.directionmessage.sent_at

Fetch message templates

必须先发送消息模板以供审批。
因此,每个消息模板都可以有以下状态:pendingapprovedrejected
如果消息模板以rejected状态进行通信,则它还带有rejected_reason状态。在

templates=api.message_templates([status="pending|approved|rejected"],[search_query='...'],[page=...])fortemplateintemplates:template.idtemplate.texttemplate.buttons# available for all Sendbee users onboarded after 11th of December 2020template.tagstemplate.keywordtemplate.languagetemplate.statustemplate.rejected_reason

Send template message

消息模板可以是纯文本或带附件的文本。
如果是带附件的,则意味着您可以将图像、视频或文档URL与文本一起发送。
当您获得消息模板的列表时,该列表中的每个模板都有一个attachment字段及其值。
附件字段值定义可以使用邮件模板发送的附件类型:

ValueDescription
imageMessage template can be sent with image URL: JPG/JPEG, PNG
videoMessage template can be sent with video URL: MP4, 3GPP
documentMessage template can be sent with document URL: PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX
nullMessage template does not support attachment URL
response=api.send_template_message(phone='+...',template_keyword='...',# every pre-created and approved message template# is identified with a keywordlanguage='...',# language keyword# example: en (for english)tags={'__tag_key__':'__tag_value__',...}# tags for template messages are parts of the message that need# to be filled with your custom data# example:# template message: "Welcome {name}! How can we help you?"# tags: {"name": contact.name}[prevent_bot_off=True|False],# if set to True, will prevent turning-off chatbot for the conversation# default system behaviour is that chatbot is turned-off[attachment='http...'])response.statusresponse.conversation_id# save this id, and when you get sent message status requests on# your webhook, you'll get this same id to identify the conversation

Send message

您可以发送文本消息或媒体消息。
对于媒体消息,支持以下格式:

^{tb2}$
response=api.send_message(phone='+...',[text='...'],# any kind of message text[media_url='...'],# URL to a media. # you need to upload it your self and send us the URL[prevent_bot_off=True|False]# if set to True, will prevent turning-off chatbot for the conversation# default system behaviour is that chatbot is turned-off)response.statusresponse.conversation_id# save this id, and when you get sent message status requests on# your webhook, you'll get this same id to identify the conversation

团队

Fetch teams

teams=api.teams([member_id='...'])forteaminteams:team.idteam.nameformemberinteam.members:member.idmember.namemember.rolemember.onlinemember.available

Fetch team members

^{pr21}$

自动化

Managing chatbot (automated responses) status settings

每个联系人都链接到与代理的对话。
对话可以由代理或聊天机器人(自动响应)处理。
每次代理或使用API向联系人发送消息时, 聊天机器人将自动关闭- 除非通过API调用将“prevent_bot_off”设置为true(请参见Send message)。
使用下面的示例根据您的用例更改聊天机器人状态。在

api.chatbot_activity(conversation_id='...',active=True|False)

Get chatbot (automated responses) status

您还可以检查聊天机器人是否打开或关闭以进行对话。在

response=api.chatbot_activity_status(conversation_id='...')response.conversation_idresponse.chatbot_active# True/False

其他

Pagination

您可以在获取某个内容列表的每个端点/方法上分页。
无论您在哪里看到[page=...],这意味着您可以像page=2page=3等分页。最好的方法是使用.next_page()方法。在

有两种方法可以检测分页结束,使用PaginationException和使用{}方法。在

Paginate using .next_page() and PaginationException:

fromsendbee_apiimportPaginationExceptionmessages=api.messages(conversation_id='...')# first pagewhileTrue:try:messages=api.messages(conversation_id='...',page=messages.next_page())exceptPaginationExceptionase:break

Paginate using .next_page() and .has_next() methods:

messages=api.messages(conversation_id='...')# first pagewhileTrue:ifnotmessages.has_next():breakmessages=api.messages(conversation_id='...',page=messages.next_page())

Raw response

如果您喜欢处理原始服务器响应,则可以在“原始数据”下找到响应字符串

fromsendbee_apiimportSendbeeApiapi=SendbeeApi('__your_api_key_here__','__your_secret_key_here__')response=api.contacts()print(response.raw_data)

Exception handling

每当发生不该有的事情时,如参数丢失、参数值无效、身份验证失败等,API都会相应地返回一个http状态码和一条错误消息。
通过使用此客户端库,将检测并获取错误消息,并引发异常,以便您可以处理它像这样:

fromsendbee_apiimportSendbeeRequestApiExceptiontry:api.send_template_message(...)exceptSendbeeRequestApiExceptionase:# handle exception

Authenticate webhook request

在Sendbee Dashboard中激活webhook URL后,我们将根据与该webhook URL链接的webhook类型开始发送对该URL的请求。
我们发出的每个请求的头中都会有授权令牌,如下所示:

{
    ...
    'X-Authorization': '__auth_token_here__',
    ...
}

要验证我们对您的webhook URL发出的请求,请从请求头获取此令牌并使用Sendbee API客户端检查它:

fromsendbee_apiimportSendbeeApiapi=SendbeeApi('__your_api_key_here__','__your_secret_key_here__')token='...'# taken from the request headerifnotapi.auth.check_auth_token(token):# error! authentication failed!

Warnings

有时APi会返回一个警告,这样您就可以得到警告。
衰减以标准输出显示:

Debugging

Debugging

此库有自己的内部调试工具。
默认情况下,它是禁用的,要启用它,请传递debug参数:

fromsendbee_apiimportSendbeeApiapi=SendbeeApi('__your_api_key_here__','__your_secret_key_here__',debug=True)

启用内部调试工具后,对API的每个请求都将以标准输出形式输出各种请求和响应数据:

Debugging

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
maven字段#getGenericType()抛出java。lang.TypeNotPresentException   用java绘制三角形的几何图形   java无法下载主题和发件人地址(rediff)   java如何使代码线程安全   java在尝试转换FileInputStream中的文件时,我遇到了一个FileNotFound异常   java Moxy和Jackson如何将Json映射到Pojo   在foreach循环中使用BufferedWriter生成新行的java问题   java为什么我的测试在单次执行中运行时间小于1秒,而在maven构建中运行时间大于20秒?   java如何显示下载附件的进度条   了解java rmi的良好实践   .net可以将Java portlet嵌入ASP。网页?   循环如何多次执行Java方法?   java如何确保用户输入在给定的有效范围内?   java单元测试定理   java如何在IntelliJ上运行外部构建项目?   JAVA:试图编写一个检查字符串是否为数字的方法。总是返回错误   javahadoop将特定键的所有map方法生成的所有值都发送到一个reduce方法,对吗?   在java中读取和使用文件