Python脚本可以运行,但是不起作用,并且不会引发任何错误

时间:2019-12-18 18:00:01

标签: python-3.6 discord.py

此程序是一个基于API的程序,已经运行了几个月,突然之间花了几天时间而没有向Discord推送任何内容。该脚本在CMD中看起来不错,但是不会引发任何错误。我想知道是否有一种方法可以消除可能的问题,例如API不稳定问题或明显的问题。该程序应该访问www.bitskins.com网站,并根据设置的参数提取外观,并每10分钟将其作为嵌入Discord频道的推送。

有两个文件运行此程序。 这是使用Bitskins API(bitskins.py)的人:

import requests, 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. Either 30 or 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>=25 and tmp.price<=200:    # Minimum discount and maximum price to look for when grabbing items. Currently set at minimum discount of 25% and maxmimum price of $200.
                    items.append(tmp)
            return items
        else:
            raise Exception(data["data"]["error_message"])
    except:
        raise Exception("Couldn't connect to BitSkins.")
# my_token = pyotp.TOTP(my_secret)
# print(my_token.now()) # in python3

这是带有Discord API(solution.py)的文件:

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

TOKEN= "Not input for obvious reasons"

API_KEY= "Not input for obvious reasons"

my_secret= 'Not input for obvious reasons'

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=0xA3FFE8)
    embed.set_author(name="Skin Bot", url="http://www.reactor.gg/",icon_url="https://pbs.twimg.com/profile_images/1050077525471158272/4_R8PsrC_400x400.jpg")
    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="Profit:", value="${}".format(item.margin), inline=True)
    embed.set_footer(text="Made by Aqyl#0001 | {}".format(datetime.now()), icon_url="https://www.discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png")
    return embed

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

@client.event
async def on_ready():

    wait_time= 60 * 10 # 10 mins in this case

    print('CSGO BitSkins Bot')
    print('Made by Aqyl#0001')
    print('Version 1.0.6')
    print('')
    print('Logged in as:')
    print(client.user.name)
    print('------------------------------------------')
    client.loop.create_task(status_task(wait_time))

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

1 个答案:

答案 0 :(得分:1)

您有一个一般性例外,这将导致捕获您确实不想捕获的异常。

================================================================================
Error executing action `run` on resource 'execute[ssh-add ~/.ssh/keyname]'
================================================================================

Mixlib::ShellOut::ShellCommandFailed
------------------------------------
Expected process to exit with [0], but received '2'
---- Begin output of ssh-add ~/.ssh/keyname ----
STDOUT: 
STDERR: Could not open a connection to your authentication agent.
---- End output of ssh-add ~/.ssh/keyname ----
Ran ssh-add ~/.ssh/keyname returned 2

这与捕获在那里出现的任何异常相同(继承try: items= bitskins.get_items(code.now(), API_KEY) for item in items: await client.send_message(client.get_channel("656913641832185878"), embed=get_embed(item)) except: pass

的异常

为避免这些问题,您应该始终捕获特定的异常。 (即BaseException)。

示例:

TypeError