如何修复错误异常以使脚本重新启动

时间:2019-06-18 21:18:57

标签: python discord.py

我有一个Discord Python3.6机器人,该机器人使用网站的API从网站中提取项目并将其推送到我的Discord服务器中。我刚刚有一些错误。有时它可以正常工作,并且会像我指定的那样每5分钟更新一次,但是在大约10次更新后崩溃。我希望它能够忽略此错误并在崩溃时重新启动,因此我不必手动进行操作。我将提供该情况的图片。

一段时间以前,我已经雇用了某人为我制作该机器人,但自从与他们失去联系以来,我对Python的了解很少,因此我无法尝试太多。

有两个文件,一个是执行所有API任务的文件,另一个是与Discord相关的文件。这个叫做bitskins.py

#!/bin/python3.5
import requests
import json
from datetime import datetime, timedelta

class Item:
    def __init__(self, item):
        withdrawable_at= item['withdrawable_at']
        price= float(item['price'])
        self.available_in= withdrawable_at- datetime.timestamp(datetime.now())
        if self.available_in< 0:
            self.available= True
        else:
            self.available= False
        self.suggested_price= float(item['suggested_price'])
        self.price= price
        self.margin= round(self.suggested_price- self.price, 2)
        self.reduction= round((1- (self.price/self.suggested_price))*100, 2)
        self.image= item['image']
        self.name= item['market_hash_name']
        self.item_id= item['item_id']

    def __str__(self):
        if self.available:
            return "Name: {}\nPrice: {}\nSuggested Price: {}\nReduction: {}%\nAvailable Now !\nLink: https://bitskins.com/view_item?app_id=730&item_id={}".format(self.name, self.price, self.suggested_price, self.reduction, self.item_id)
        else:
            return "Name: {}\nPrice: {}\nSuggested Price: {}\nReduction: {}%\nAvailable in: {}\nLink: https://bitskins.com/view_item?app_id=730&item_id={}".format(self.name, self.price, self.suggested_price, self.reduction, str(timedelta(seconds= self.available_in)), self.item_id)

    def __lt__(self, other):
        return self.reduction < other.reduction
    def __gt__(self, other):
        return self.reduction > other.reduction


def get_url(API_KEY, code):
    PER_PAGE= 30 # the number of items to retrieve. goes from 30 to 480
    return "https://bitskins.com/api/v1/get_inventory_on_sale/?api_key="+ API_KEY+"&code=" + code+ "&per_page="+ str(PER_PAGE)

def get_data(url):
    r= requests.get(url)
    data= r.json()
    return data

def get_items(code, API_KEY):
    url= get_url(API_KEY, code)
    try:
        data= get_data(url)
        if data['status']=="success":
            items= []
            items_dic= data['data']['items']
            for item in items_dic:
                tmp= Item(item)
                if tmp.reduction>=20:
                    items.append(tmp)
            return items
        else:
            raise Exception(data["data"]["error_message"])
    except:
        print("Couldn't connect to Bitskins")

# my_token = pyotp.TOTP(my_secret)
# print(my_token.now()) # in python3

这是第二个文件解决方案。py

#!/bin/python3.5
import bitskins
import discord
import pyotp, base64, asyncio
from datetime import timedelta, datetime

TOKEN= "NOT SHOWING THE BOT TOKEN"

API_KEY= "NOT SHOWING API KEY"

my_secret= 'NOT SHOWING MY SECRET KEY'

client= discord.Client()

def get_embed(item):
    embed=discord.Embed(title=item.name, url= "https://bitskins.com/view_item?app_id=730&item_id={}".format(item.item_id), color=0x75bacf)
    embed.set_author(name="Skin Bot", url="https://www.reactor.gg/",icon_url="https://cdn.discordapp.com/avatars/574801125765808131/ffeb4b83f75977f6a8f20c5ecb5f0164.png")
    embed.set_thumbnail(url=item.image)
    embed.add_field(name="Price :", value="${}".format(item.price))
    embed.add_field(name="Discount :" , value="{}%".format(item.reduction), inline=True)
    if item.available:
        tmp= "Instantly Withdrawable"
    else:
        tmp= str(timedelta(seconds= item.available_in))
    embed.add_field(name="Availability:", value=tmp, inline=True)
    embed.add_field(name="Suggested Price :", value="${}".format(item.suggested_price), inline=True)
    embed.add_field(name="Margin :", value="${}".format(item.margin), inline=True)
    embed.set_footer(text="Made By Stahp")
    return embed

async def status_task(wait_time= 60* 5):
    while True:
        print("Updated on: {}".format(datetime.now()))
        code= pyotp.TOTP(my_secret)
        items= bitskins.get_items(code.now(), API_KEY)
        for item in items:
            await client.send_message(client.get_channel("564815517601234953"), embed=get_embed(item))
        await asyncio.sleep(wait_time)

@client.event
async def on_ready():
    wait_time= 60 * 10 # 10 mins in this case
    print("Logged in as")
    print(client.user.name)
    print(client.user.id)
    print("------")
    client.loop.create_task(status_task(wait_time))

try:
    client.run(TOKEN)
except:
    print("Couldn't connect to the Discord Server")

这是我收到的错误的屏幕截图:https://gyazo.com/7c4ba03e8a9e182bf79c625c3455dd5b

1 个答案:

答案 0 :(得分:0)

如果get_items中存在异常,则except子句不会返回任何内容,这意味着它会隐式返回None。您应该返回一个空列表:

def get_items(code, API_KEY):
    url= get_url(API_KEY, code)
    try:
        data= get_data(url)
        if data['status']=="success":
            items= []
            items_dic= data['data']['items']
            for item in items_dic:
                tmp= Item(item)
                if tmp.reduction>=20:
                    items.append(tmp)
            return items
        else:
            raise Exception(data["data"]["error_message"])
    except Exception as e:
        print("Couldn't connect to Bitskins")
        print(e)
        return []