Call Dingding interface to realize robot push message

Author: Lydia, Created: 2022-12-20 08:57:16, Updated: 2023-09-20 09:09:55

img

Call Dingding interface to realize robot push message

1. Summary

In real transactions, in order to know the FMZ Quant robot trading status in time, sometimes we need to send the transaction results executed by the robot to WeChat, email, SMS, etc. However, there are hundreds of various kinds of information every day, which makes it insensitive to these information, leading to the failure of timely collection of important information. Therefore, this article implements robot push message by calling Dingding group interface.

2. Dingding group robot

The Dingding group robot is an advanced extension function. As long as there is a Dingding account, you can use it. It can aggregate the third-party information into the Dingding group to achieve automatic information synchronization. It supports the customized access of Webhook protocol, and aggregate the reminder, alert and other information into the Dingding group through the FMZ Quant robot. Three message formats and five message types are supported: text, link and markdown. The same message can also be sent to multiple Dingding groups at the same time. Refer to the official link: https://ding-doc.dingtalk.com/doc#/serverapi2/ye8tup

3. Create robot

Step 1: Create a Dingding group

img

Each customized robot created in the Dingding group will generate a unique hook address, which is called a WebHook address. The Dingding group will receive a message by pushing a message to the WebHook address. Let’s take the PC version of Dingding as an example. First, click the “+” sign on the top left to start a group chat. If you just want to accept the message yourself, you can select two people and kick them out. Fill in the group name: “FMZ Robot”, and select an ordinary group as the group type.

Step 2: Add Dingding group robot

Click the avatar, select Robot Management, then select Custom, and click Add. Custom robot name: “FMZ”, added to the newly created Dingding group. The robot supports three security settings:

img

  • User defined keyword: information will be synchronized only if it contains this keyword.
  • Signature: equivalent to setting a password.
  • IP address: the IP address segment of fixed third-party information.

If it is only used for reminder or alert, select the user-defined keyword. The keyword we define here is “:”, that is, when the information pushed by the FMZ Quant Robot contains “:”, the information will be pushed to the Dingding group. Then click Agree to complete the agreement. Finally, copy the Webhook address for backup.

4. Code implementation

After obtaining the Webhook address, we can send the information to the Dingding group by sending an HTTP POST request to the address in the FMZ Quant strategy. Note that the character set encoding must be set to UTF-8 when a POST request is initiated.

import requests
import json
from datetime import datetime, timedelta, timezone


# Output information to Dingding group
def msg(text):
    token ="0303627a118e739e628bcde104e19cf5463f61a4a127e4f2376e6a8aa1156ef1"
    headers = {'Content-Type': 'application/json;charset=utf-8'}  # Request header
    api_url = f"https://oapi.dingtalk.com/robot/send?access_token={token}"
    json_text = {
        "msgtype": "text",  # Message type
        "text": {
            "content": text
        }
    }
    # Send and print messages
    Log(requests.post(api_url, json.dumps(json_text), headers=headers).content)

    
# Test functions
def onTick():
    arr = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC']  # Mainstream digital currencies
    # Get the time of East Zone 8
    bj_dt = str(datetime.now().astimezone(timezone(timedelta(hours=8))))
    bj_dt = bj_dt.split('.')[0]  # Time of processing
    text = f'{bj_dt}\n'  # Define information content
    for i in arr:  # Loop mainstream digital currency array
        exchange.IO("currency", f"{i}_USDT")  # Switch trading pairs
        ticker = exchange.GetTicker().Last  # Get the latest price
        if i == 'LTC':
            full = ' :'
        else:
            full = ':'
        text = text + f"{i}/USDT{full}${ticker}\n"  # Processing information content
    msg(text)  # Call msg function to output information
    

# Strategy entrance
def main():
    while True:  # Enter infinite loop 
        onTick()  # Execute onTick function
        Sleep(1000 * 60)  # Sleep for one minute

When a customized robot synchronizes information, it can set mobile phone number to @ multiple members in the group. When the group member receives the message, there will be an @ message reminder. The reminder will still be notified even if the No Disturb Session is set.

# Output information to Dingding group
def msg(text):
    token = "0303627a118e739e628bcde104e19cf5463f61a4a127e4f2376e6a8aa1156ef1"
    headers = {'Content-Type': 'application/json;charset=utf-8'}  # Request header
    api_url = f"https://oapi.dingtalk.com/robot/send?access_token={token}"
    json_text = {
        "msgtype": "text",  # Message type
        "text": {
            "content": text
        },
        "at": {
            "atMobiles": [
                "16666666666",  # Phone number of the @
                "18888888888"  # Phone number of the @
            ],
            "isAtAll": False  # Not @ Everyone
        }
    }
    # Send and print messages
    Log(requests.post(api_url, json.dumps(json_text), headers=headers).content)

5. Test robot

In the above code, we wrote a case to obtain the price of mainstream digital currency every one minute and push these information to the Dingding group: img


Related

More