当需要对全局变量进行更改时,则会出现不安全的情况
# -*- coding: utf-8 -*-
"""================================================================================================================
@date : 2022/8/17 16:06
@function : 自动转发用户正常入线chat至指定在线客服
================================================================================================================"""
import json
import time
import requests
from loguru import logger
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from utils.common import open_gsheet
class AUTO_TRANSFER_CHAT:
def __init__(self):
self.headers = {
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'authorization': '',
'content-type': 'text/plain;charset=UTF-8',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
}
self.shop_id_dict = {
'476792408':'CO', '446091597':'TH', '476792515':'CL', '446090097':'TW',
'446089250':'VN', '538890515':'PL', '426378412':'BR', '445275287':'SG', '426377685':'PH',
'445279067':'MY', '868341135': 'MY_2','426379311':'MX', '558513120':'ES'
}
def get_auths(self):
"""获取在线客服"""
sheet = open_gsheet('L.OP3.3-Mass Outbound Chat Tool[Lovito]', 'Online status')
datas = sheet.get_values('A2:E')
account_auths = []
for data in datas:
account_auths.append((data[0].strip(), data[4].strip()))
logger.info(f'account_auths: {len(account_auths)}, {account_auths[:5]}')
return account_auths
def _request_get(self, url, account):
i = 0
while i < 3:
try:
response = requests.get(url, headers=self.headers, timeout=30)
response = response.json()
return response
except Exception as e:
i += 1
print(f'try {i} times, {account} {e.args}')
else:
raise Exception(f'{account} request error')
def _request_put(self, url, payload, to_name):
i = 0
while i < 3:
try:
response = requests.put(url, data=json.dumps(payload), headers=self.headers, timeout=30)
return response
except:
i += 1
print(f'try {i} times, {to_name}')
else:
raise Exception(f'{to_name} transfer error')
def get_all_unread(self, account_auth, index, l):
account, auth = account_auth[0], account_auth[1]
url = 'https://seller.ph.shopee.cn/webchat/api/v1.2/subaccount/conversations?direction=older&_s=1&type=unread'
self.headers['authorization'] = auth + account # 多线程更改全局变量不安全!这里的authorization和account不一定和lovitocs:outbound_receive201相同
if account == 'lovitocs:outbound_receive201':
print(account, self.headers)
response = self._request_get(url, account)
try:
conversations = [(i['id'], i['shop_id'], i['to_id'], i['to_name']) for i in response]
except:
raise Exception(response)
logger.info(f'{index}/{l} {account}, conversations: {len(conversations)}, {conversations}')
return conversations
def parse_exception(self, obj):
result = obj.result()
if result:
print(result)
def treat_one_account_unit(self, account_auth, index, l):
account, auth = account_auth[0], account_auth[1]
th_timestamp = int(time.mktime(time.strptime((datetime.now()).strftime('%Y-%m-%d') + ' 10:30:00', '%Y-%m-%d %H:%M:%S')))
vn_timestamp = int(time.mktime(time.strptime((datetime.now()).strftime('%Y-%m-%d') + ' 08:30:00', '%Y-%m-%d %H:%M:%S')))
now = time.time()
if (now > th_timestamp) or (now > vn_timestamp and 'agentvncb' in account) or 'lovitocs:outbound_receive' in account:
pass
else:
return
self.get_all_unread(account_auth, index, l)
def treat_one_account(self, index, l, account_auth):
logger.info(f'{index}/{l} {account_auth[:2]}')
self.treat_one_account_unit(account_auth, index, l)
def main(self):
account_auths = [('lovitocs:outbound_receive201', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVfdGltZSI6MTY2OTY3NDE2NSwiaWQiOiIyZWMxZTA4ZS02ZjZiLTExZWQtODc2Yi1mNGVlMDgwZWU3ZDAifQ.raDQAjwn_BNRqZrKc7DtHkdLVWJad80gHSoDGT7VOkU'), ('lovitocs:outbound_receive202', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVfdGltZSI6MTY2OTY3NDE3MCwiaWQiOiIzMTk4YTYxMS02ZjZiLTExZWQtYjUwMi1mNGVlMDgxNmQ1MGMifQ.dEnbrfmgVuD3dECXxpkMPeLCF-o42wV9UCyJIfo2Et8'), ('lovitocs:outbound_receive203', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVfdGltZSI6MTY2OTY3NDIwMSwiaWQiOiI0NDU2ZGZhZi02ZjZiLTExZWQtYTQ2Ni1hZTc2MDgzM2U3ZTEifQ.AFnmPrgdxt7d216pYdURegu5XQ1q8NBcIbM3ndlYHes'), ('lovitocs:outbound_receive204', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVfdGltZSI6MTY2OTY3NDIzMSwiaWQiOiI1NjAwNmM0Ni02ZjZiLTExZWQtOWMxNS1mNGVlMDgwZDI2NGQifQ.8p873dTdrlyF6PTGB4-46jPVfstR0JrNTuZWQCD9LF0'), ('lovitocs:outbound_receive205', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVfdGltZSI6MTY2OTY3NDIzMiwiaWQiOiI1NmIwYTY3Zi02ZjZiLTExZWQtODc5Zi1mNGVlMDgxNDI4YmUifQ.v79Xoeg0v6q_xaxC6RMpfJmSWQKtdc9D91N7SC1JgA0')]
exector = ThreadPoolExecutor(max_workers=10)
for index, account_auth in enumerate(account_auths):
if index < 0:
continue
exector.submit(self.treat_one_account, index, len(account_auths), account_auth).add_done_callback(self.parse_exception)
exector.shutdown(wait=True)
if __name__ == '__main__':
a = AUTO_TRANSFER_CHAT()
a.main()
改进措施:不直接修改全局变量:
header = self.headers.copy()
header['authorization'] = auth + account