用python转发安卓短信到微信

Posted on 五 05 十月 2018 in Python

  • 最近换了个单卡的手机,之前双卡就只能装一张卡,就需要将短信实时转发到微信上,于是就用方糖来转发,在安卓手机上安装termux,然后如果手机是root过后的,就可以直接读取短信数据库,短信数据库位置需要自己找,如果没有root可以安装termux-api这个软件来读取短信,我已经用了好几个月了,挺方便的,大致效果如下

手机短信位置,小米5,安卓7.1.2 LineageOS14.1

  • 数据库位置/data/data/com.android.messaging/databases/bugle_db
  • 其中主要表和对应关系如下:

    • conversationsparticipant_normalized_destination为发件人号码
    • conversationsname通讯录内发件人备注
    • conversationssnippet_text为短信内容
    • conversationssort_timestamp为发件时间,unix时间戳,毫秒
    • conversationslatest_message_idmessages表的_id
    • messagesread表示短信已被读(打开当前短信会话)
    • messagesseen表示短信已被读(未打开当前短信会话,单已在短信界面被预览)
  • 简单的代码,用方糖转发短信,如果同样的数据库结构的话,可以直接拿过去用,记得用screen后台运行

import requests
import sqlite3
import time
import datetime


def timestamp_datatime(value,t_format = '%Y-%m-%d %H:%M'):
    value = time.localtime(value)  
    dt = time.strftime(t_format,value)  
    return dt

def now_date():
    nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return nowTime

class SMS(object):

    def __init__(self,db):
        self.db = sqlite3.connect(db)
        self.web_hook = "https://sc.ftqq.com/SCU1111111111111111111111111111111111.send"

    def execute(self,sql):
        cur = self.db.cursor()
        cur.execute(sql)
        data = cur.fetchall()
        cur.close()
        return data

    def execute_with_commit(self,sql):
        cur = self.db.cursor()
        cur.execute(sql)
        self.db.commit()
        cur.close()

    def set_all_readed(self):
        sql = "update messages set read = 1  where read = 0;"
        self.execute_with_commit(sql)

    def set_read(self,messages_id):
        sql = f"update messages set read = 1  where _id = '{messages_id}';"
        self.execute_with_commit(sql)

    def get_unreaded_msgs(self):
        sql = "select _id from messages where read = 0;"
        _ids = self.execute(sql)
        ids = [i[0] for i in _ids]
        return ids

    def get_messages(self,msg_id):
        sql = f"select participant_normalized_destination,name,snippet_text,sort_timestamp from conversations where latest_message_id={msg_id};"
        try:
            data = self.execute(sql)[0]
        except Exception as E:
            print(E)
            return false
        participant_normalized_destination = data[0]
        name = data[1]
        snippet_text = data[2]
        sort_timestamp = int(data[3]/1000)
        date_time = timestamp_datatime(sort_timestamp)
        text = f'''
        发件人:{participant_normalized_destination}
        备注:{name}
        时间:{date_time}
        内容:{snippet_text}

        '''
        return text

    def send(self, text):
        payload = {'text': '安卓短信转发', 'desp':text}
        r = requests.get(self.web_hook, params=payload)
        if r.status_code == 200:
            return True
        return False


if __name__ == "__main__":
    sms = SMS("/data/data/com.android.messaging/databases/bugle_db")
    while 1:
        ids = sms.get_unreaded_msgs()
        for i in ids:
            text = sms.get_messages(i)
            if text:
                if sms.send(text):
                    sms.set_read(i)
                    print(text)
        time.sleep(2)
        now = now_date()
        print(now+"我还活着...")