コード例 #1
0
def send_message(tel="18611846371", module="hadoop", message="error"):
    # 从https://account.console.aliyun.com/#/secure获取$YourAccountid
    # 从https://ak-console.aliyun.com/#/accesskey获取$YourAccessId和$YourAccessKey
    # 从http://$YourAccountId.mns.cn-hangzhou.aliyuncs.com获取$YourMNSEndpoint, eg. http://1234567890123456.mns.cn-hangzhou.aliyuncs.com
    YourMNSEndpoint = "http://1111641897067585.mns.cn-hangzhou-internal.aliyuncs.com/"
    YourAccessId = "LTAIyhZeIPt8ivJd"
    YourAccessKey = "myvAcplJMk32PHIt2DSmWhRqcz6CHv"
    my_account = Account(YourMNSEndpoint, YourAccessId, YourAccessKey)

    YourTopicName = "sms.topic-cn-hangzhou"
    my_topic = my_account.get_topic(YourTopicName)
    #print my_topic
    '''
    Step 2. 设置SMS消息体(必须)
    注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
    '''
    msg_body1 = "报警短信消息"
    '''
    Step 3. 生成SMS消息属性,single=False表示每个接收者参数不一样,
    single=True表示每个接收者参数一样
    '''
    # 3.1 设置SMSSignName和SMSTempateCode
    YourSignName = "app运营助手"
    YourSMSTemplateCode = "SMS_32785106"

    direct_sms_attr1 = DirectSMSInfo(free_sign_name=YourSignName,
                                     template_code=YourSMSTemplateCode,
                                     single=True)
    # 3.2 指定接收短信的手机号并指定发送给该接收人的短信中的参数值(在短信模板中定义的)
    cur_time = time.strftime('%H:%M:%S', time.localtime())  #变量内容不能太长
    direct_sms_attr1.add_receiver(receiver=tel)
    direct_sms_attr1.set_params({
        "machine": "短视频",
        "module": module,
        "time": cur_time,
        "message": message
    })

    #Step 5. 生成SMS消息对象
    msg1 = TopicMessage(msg_body1, direct_sms=direct_sms_attr1)

    re_msg = my_topic.publish_message(msg1)
    #print "Publish Message Succeed. MessageBody:%s MessageID:%s" % (msg_body1, re_msg.message_id)

    return 0
コード例 #2
0
def aliyunMsg(user, *args):
    code, product = args
    my_account = Account(Config.MNS_ENDPOINT, Config.MNS_ACCESSID,
                         Config.MNS_ACCESSKEY)
    my_topic = my_account.get_topic(Config.MNS_TOPIC)
    msg_body1 = "sms-message1."
    direct_sms_attr1 = DirectSMSInfo(free_sign_name=Config.MNS_SIGN,
                                     template_code=Config.MNS_TEMPLATE_CODE,
                                     single=True)
    direct_sms_attr1.add_receiver(receiver=user)
    direct_sms_attr1.set_params({"code": code, "product": product})
    msg1 = TopicMessage(msg_body1, direct_sms=direct_sms_attr1)
    try:
        re_msg = my_topic.publish_message(msg1)
        print "Publish Message Succeed. MessageBody:%s MessageID:%s" % (
            msg_body1, re_msg.message_id)
    except MNSExceptionBase, e:
        if e.type == "TopicNotExist":
            print "Topic not exist, please create it."
            sys.exit(1)
        print "Publish Message Fail. Exception:%s" % e
コード例 #3
0
ファイル: test.py プロジェクト: DjangSon/aliyun
# coding: utf-8
import sys
from mns.account import Account
from mns.topic import DirectSMSInfo, TopicMessage
from mns.mns_exception import MNSExceptionBase
accid = 'LTAIf6atnIup14AK'
acckey = 'zfoeCi2Au0le7vUbsFOmEVtPrtlfZf'
endpoint = 'http://1771999519197750.mns.cn-hangzhou.aliyuncs.com/'
topic_name = 'sms.topic-cn-hangzhou'
my_account = Account(endpoint, accid, acckey)
my_topic = my_account.get_topic(topic_name)
'''
Step 2. 设置SMS消息体(必须)
注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
'''
msg_body1 = "sms-message1."
'''
Step 3. 生成SMS消息属性,single=False表示每个接收者参数不一样,
'''
# 3.1 设置SMSSignName和SMSTemplateCode
direct_sms_attr1 = DirectSMSInfo(free_sign_name='宁师生活网', template_code='SMS_69460049', single=False)
# 3.2 指定接收短信的手机号并指定发送给该接收人的短信中的参数值(在短信模板中定义的)
direct_sms_attr1.add_receiver(receiver='18150850025', params={'code': '123456'})
'''
#Step 5. 生成SMS消息对象
'''
msg1 = TopicMessage(msg_body1, direct_sms=direct_sms_attr1)
print(direct_sms_attr1.sms_params)
try:
    '''
    Step 6. 发布SMS消息
コード例 #4
0
ファイル: sample.py プロジェクト: DarkIsComing/aliyun-sdk
    my_queue.batch_delete_message(receipt_handle_list)
    sys.stdout.write("Batch Delete Message Succeed.\n")
except MNSExceptionBase as e:
    sys.stderr.write("Batch Delete Message Fail!\nException:%s\n\n" % e)
    sys.exit(1)

#删除队列
try:
    my_queue.delete()
    sys.stdout.write("Delete Queue Succeed!\n\n")
except MNSExceptionBase as e:
    sys.stderr.write("Delete Queue Fail!\nException:%s\n\n" % e)
    sys.exit(1)

##############Topic 相关操作#####################
my_topic = my_account.get_topic(
    "MyTopic-%s" % time.strftime("%y%m%d-%H%M%S", time.localtime()))

#创建主题
## maximum_message_size 消息的最大长度      10240Byte
topic_meta = TopicMeta()
topic_meta.set_maximum_message_size(10240)
try:
    topic_url = my_topic.create(topic_meta)
    sys.stdout.write("Create Topic Succeed!\nTopicURL:%s\n\n" % topic_url)
except MNSExceptionBase as e:
    sys.stderr.write("Create Topic Fail!\nException:%s\n\n" % e)
    sys.exit(1)

#修改主题属性
## maximum_message_size 消息的最大长度      6144Byte
topic_meta = TopicMeta()
コード例 #5
0
ファイル: sample.py プロジェクト: lvyaojia/mns
    my_queue.batch_delete_message(receipt_handle_list)
    sys.stdout.write("Batch Delete Message Succeed.\n")
except MNSExceptionBase, e:
    sys.stderr.write("Batch Delete Message Fail!\nException:%s\n\n" % e)
    sys.exit(1)

#删除队列
try:
    my_queue.delete()
    sys.stdout.write("Delete Queue Succeed!\n\n")
except MNSExceptionBase, e:
    sys.stderr.write("Delete Queue Fail!\nException:%s\n\n" % e)
    sys.exit(1)

##############Topic 相关操作#####################
my_topic = my_account.get_topic("MyTopic-%s" % time.strftime("%y%m%d-%H%M%S", time.localtime()))

#创建主题
## maximum_message_size 消息的最大长度      10240Byte
topic_meta = TopicMeta()
topic_meta.set_maximum_message_size(10240)
try:
    topic_url = my_topic.create(topic_meta)
    sys.stdout.write("Create Topic Succeed!\nTopicURL:%s\n\n" % topic_url)
except MNSExceptionBase, e:
    sys.stderr.write("Create Topic Fail!\nException:%s\n\n" % e)
    sys.exit(1)

#修改主题属性
## maximum_message_size 消息的最大长度      6144Byte
topic_meta = TopicMeta()
コード例 #6
0
ファイル: publishmessage.py プロジェクト: lvyaojia/mns
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")

import time
from sample_common import MNSSampleCommon
from mns.account import Account
from mns.topic import *

#从sample.cfg中读取基本配置信息
## WARNING: Please do not hard code your accessId and accesskey in next line.(more information: https://yq.aliyun.com/articles/55947)
accid,acckey,endpoint,token = MNSSampleCommon.LoadConfig()

#初始化 my_account, my_topic
my_account = Account(endpoint, accid, acckey, token)
topic_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleTopic"
my_topic = my_account.get_topic(topic_name)

#循环发布多条消息
msg_count = 3
print "%sPublish Message To Topic%s\nTopicName:%s\nMessageCount:%s\n" % (10*"=", 10*"=", topic_name, msg_count)

for i in range(msg_count):
    try:
        msg_body = "I am test message %s." % i
        msg = TopicMessage(msg_body)
        re_msg = my_topic.publish_message(msg)
        print "Publish Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id)
    except MNSExceptionBase,e:
        if e.type == "TopicNotExist":
            print "Topic not exist, please create it."
            sys.exit(1)
コード例 #7
0
#coding:utf-8
import os
from flask import Flask, jsonify, request
from mns.account import Account
from mns.topic import DirectSMSInfo, TopicMessage, MNSExceptionBase

app = Flask(__name__)
account = Account(os.getenv('END_POINT'), os.getenv('ACCESS_ID'),
                  os.getenv('ACCESS_KEY'))
topic = account.get_topic(os.getenv('TOPIC'))
accessToken = os.getenv('ACCESS_TOKEN')


class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv


@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
コード例 #8
0
ファイル: ali_mns.py プロジェクト: Johnmc104/Python_JD
from mns.queue import *
from mns.topic import *
from mns.subscription import *
import ConfigParser

#获取配置信息
accessKeyId =  ""
accessKeySecret =  ""
endpoint = " "
securityToken = ""


#初始化my_account
my_account = Account("", "", "")
my_queue = my_account.get_queue("MyQueue-%s" % time.strftime("%y%m%d-%H%M%S", time.localtime()))
my_topic = my_account.get_topic("sms.topic-cn-shanghai")

'''
天气查询
'''
reload(sys)
sys.setdefaultencoding('utf-8')

#查询城市ID
baseurl = 'https://free-api.heweather.com/v5/'
ikey = '1be15036695c4206b949a3c1ffc7ce72'

print ("Please tell us city name")
city_n = raw_input("Enter your city nmae: ")

url = str(baseurl) + 'search?city=' + str(city_n) + '&key=' + str(ikey)
コード例 #9
0
# -*- coding:utf-8 -*-
from mns.account import Account
from mns.topic import DirectSMSInfo, TopicMessage, MNSExceptionBase
import sys

AccessId = "******"
AccessKey = "******"
MNSEndpoint = "http://******.mns.cn-beijing.aliyuncs.com"
sign_name = "******"
template_name = "******"
recv_phone = "******"
monitor_params = {"hostname": "web", "resource": "cpu", "details": "CpuLoad"}

my_account = Account(MNSEndpoint, AccessId, AccessKey)
my_topic = my_account.get_topic("sms.topic-cn-beijing")
msg_body = "sms-message."

sms = DirectSMSInfo(free_sign_name=sign_name,
                    template_code=template_name,
                    single=False)
sms.add_receiver(receiver=recv_phone, params=monitor_params)

msg = TopicMessage(msg_body, direct_sms=sms)

try:
    re_msg = my_topic.publish_message(msg)
    print "Publish Message Succeed.MessageBody:%s MessageID: %s" % (
        msg_body, re_msg.message_id)
except MNSExceptionBase, e:
    if e.typem == "TopicNotExist":
        print "Topic not exist, please create it."