效果图
文章出处
原文如上,在以上代码中改的,改动以下地方:
- 天气和每日一句都改成了天行的,自己去天行API申请,填上key和城市代码。
- 图床用了路过的,填上路过登录账号和密码即可。
- 推送用了dingtalkchatbot包,填上webhook地址secret。
- 任意找两张图’moban.jpg,大小为800-1280,icons.png大小为200-400,放到img文件夹下。
代码如下:
# coding: utf-8
import requests,json,re,io,time,hmac,hashlib,base64,random
from urllib.request import urlopen
from datetime import datetime
from PIL import Image,ImageFilter,ImageFont,ImageDraw
from bs4 import BeautifulSoup
from dingtalkchatbot.chatbot import DingtalkChatbot, ActionCard, CardItem
import http.client, urllib
from up2b.up2b_lib.utils import logger
from up2b.up2b_lib.up2b_api.imgtu import Imgtu
from time import sleep
#高斯模糊类
class MyGaussianBlur(ImageFilter.Filter):
name = "GaussianBlur"
def __init__(self, radius=2, bounds=None):
self.radius = radius
self.bounds = bounds
def filter(self, image):
if self.bounds:
clips = image.crop(self.bounds).gaussian_blur(self.radius)
image.paste(clips, self.bounds)
return image
else:
return image.gaussian_blur(self.radius)
#卡片生成类
class myCard:
def __init__(self):
self.img_url='img/moban.jpg' #800*1280
self.icon_url = 'img/icons.png' #200*400
#纵向间距
self.magrinImgTop=150
#横向间距
self.magrinImgLeft=30
self.background_height=0
#加载底图
def loadMoban(self):
self.img = Image.open(self.img_url)#.convert("RGBA")
self.width,self.height=self.img.size
#加载图片
def loadBackground(self,background_url):
self.background=Image.open(background_url).convert("RGBA")
#加载小图
def loadIcon(self):
self.icon=Image.open(self.icon_url).convert("RGBA")
#高斯模糊图片作为背景
def drawBlur(self):
backflur = self.background.resize((self.width,self.height), resample=3).filter(MyGaussianBlur(radius=30))
self.img.paste(backflur,(0, 0))
#添加标题
def drawTitle(self):
draw = ImageDraw.Draw(self.img)
#文字行距
magrinTop=20
size=150
title_font = ImageFont.truetype('fzqk.TTF', size)
x=self.width/4-size+self.magrinImgLeft
y=self.magrinImgTop
draw.text((x,y), '早', font=title_font, fill='#ffffff')
size=150
title_font = ImageFont.truetype('fzqk.TTF', size)
x=x
y=y+size+magrinTop
draw.text((x,y), '安', font=title_font, fill='#ffffff')
#添加图片
def drawBackground(self):
x=0
y=self.magrinImgTop*2
srcwidth,srcheight=self.background.size
height=int(srcheight*self.width/srcwidth)
#重设图片尺寸
background = self.background.resize((self.width, height),Image.ANTIALIAS)
#创建圆形遮罩
alpha_layer = Image.new('L', (self.width, height), 0)
draw = ImageDraw.Draw(alpha_layer)
draw.ellipse((self.width/2-100,0, self.width-30, height), fill=255)
self.img.paste(background,(x,y),alpha_layer)
self.background_height=y+height
#添加文字
def drawText(self,tmp,weather,week):
draw = ImageDraw.Draw(self.img)
#文字行距
magrinTop=180
x=int(self.width/2)-self.magrinImgLeft
y=self.background_height+self.magrinImgTop
font = ImageFont.truetype('fzqk.TTF', 80)
draw.text((x,y), tmp, font=font, fill='#ffffff')
x=x
y=y+magrinTop
font = ImageFont.truetype('fzqk.TTF', 50)
draw.text((x,y), weather+' '+week, font=font, fill='#ffffff')
#添加小图
def drawIcon(self):
x_magrinImgLeft_add=30
x=self.magrinImgLeft+x_magrinImgLeft_add
y=int(self.height/2)+self.magrinImgTop
self.img.paste(self.icon,(x,y),self.icon)
#保存到本地
def saveCard(self):
save_name = 'img/'+str(datetime.today()).split()[0]+'.jpg'
self.img.save(save_name)
return save_name
def drawCard(self):
self.loadMoban()
background_url=getBingBackground()
self.loadBackground(background_url)
self.loadIcon()
self.drawBlur()
self.drawTitle()
self.drawBackground()
self.drawIcon()
text=getWeatherNow()
if text!=0:
self.drawText(text['tmp'],text['weather'],text['week'])
else:
print('Error:getWeatherNow() false')
#卡片发送类
class sendCard:
def __init__(self,save_name):
self.upload(save_name)
self.text=getOneData()
def upload(self,img):
im = Imgtu()
username = ""
password = ""
whynot = im.login(username,password)
if(whynot):
print("登录成功...")
sleep(2)
print("正在上传图片...")
res = im.upload_image(img)
if isinstance(res, str):
self.img_url=res
print("上传成功...")
else:
logger.fatal("上传出错:%s", res)
#发送Markdown
def sendImg(self):
webhook = ''
secret = ''
xiaoding = DingtalkChatbot(webhook,secret=secret,pc_slide=True,fail_notice=False)
xiaoding.send_markdown(title='测试', text='> ## **<font color=#FF0000>测试**</font>\n\n'
'> ![海报]({})\n\n'
'> **<font color=#000000>{}**</font>'.format(self.img_url,self.text)
,is_at_all=False)
#获取天行天气
def getWeatherNow():
conn = http.client.HTTPSConnection('apis.tianapi.com') #接口域名
key = ''
city = ''
params = urllib.parse.urlencode({'key': key,'city': city,'type':'1'})
headers = {'Content-type':'application/x-www-form-urlencoded'}
conn.request('POST','/tianqi/index',params,headers)
tianapi = conn.getresponse()
result = tianapi.read()
data = result.decode('utf-8')
dict_data = json.loads(data)
if(dict_data.get('code')==200):
weather=dict_data.get('result')
lowest_tmp=weather.get('lowest')
highest_tmp=weather.get('highest')
tmp = lowest_tmp + '至' + highest_tmp
weather=weather.get('weather')
week = datetime.now().weekday()
weekdict = {0 : '星期一',1 : '星期二',2 : '星期三',3 : '星期四',4 : '星期五',5 : '星期六',6 : '星期天',}
return ({'tmp':tmp,'weather':weather,'week':weekdict[week]})
else:
print('now_info.status_code is not 200')
return 0
#获取bing每日壁纸
def getBingBackground():
url_api = 'https://api.cyrilstudio.top/bing/image.php/bing?rand=false'
url = urlopen(url_api).geturl()
image_bytes = urlopen(url).read()
data_stream = io.BytesIO(image_bytes)
return data_stream
#获取天行每日一句
def getOneData():
msg=""
conn = http.client.HTTPSConnection('apis.tianapi.com') #接口域名
key = ''
params = urllib.parse.urlencode({'key':'key','num':'1'})
headers = {'Content-type':'application/x-www-form-urlencoded'}
conn.request('POST','/dictum/index',params,headers)
tianapi = conn.getresponse()
result = tianapi.read()
data = result.decode('utf-8')
dict_data = json.loads(data)
dict_content=dict_data["result"]["list"][0]["content"]
dict_name=dict_data["result"]["list"][0]["mrname"]
msg = dict_name + ":" + dict_content
return msg
if __name__ == '__main__':
#生成卡片,在./img进行操作
card=myCard()
card.drawCard()
save_name=card.saveCard()
#发送卡片
post=sendCard(save_name)
post.sendImg()
print("运行完毕")