我有一个链接到 GitHub 存储库的 PyCharm 项目。当您尝试编辑任何文件时,会出现一个警告窗口:
从它我了解到该文件不在项目中。问题是如何在那里添加它?
我运行了命令git add .,但没有帮助。
为什么会出现错误?
import pafy
def get_playlist(url):
playlist = pafy.get_playlist(url)
return playlist['items']
if __name__ == '__main__':
yt_url = input('Введите ссылку: ')
p = get_playlist(yt_url)
关联:
https://www.youtube.com/playlist?list=PL-Sp30dZBoZ2nBqUkUB3C93YHiVJCp-GY
错误:
Traceback (most recent call last):
File "D:/pyprojects/yt_dl/test2.py", line 11, in <module>
p = get_playlist(yt_url)
File "D:/pyprojects/yt_dl/test2.py", line 5, in get_playlist
playlist = pafy.get_playlist(url)
File "D:\pyprojects\venv\lib\site-packages\pafy\playlist.py", line 58, in get_playlist
allinfo = fetch_decode(url) # unicode
File "D:\pyprojects\venv\lib\site-packages\pafy\pafy.py", line 67, in fetch_decode
req = g.opener.open(url)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 531, in open
response = meth(req, response)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 640, in http_response
response = self.parent.error(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 563, in error
result = self._call_chain(*args)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 502, in _call_chain
result = func(*args)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 755, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 531, in open
response = meth(req, response)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 640, in http_response
response = self.parent.error(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 502, in _call_chain
result = func(*args)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
我有一个带有嵌套函数的命令on_message。满足特定条件时如何停止它?
例子:
@bot.command()
async def test(ctx):
await ctx.send('started')
@bot.event
async def on_message(mes):
if mes.author.bot:
return
msg = mes.content
if msg != 'break':
await ctx.send('do something')
else:
await ctx.send('stoped')
await bot.process_commands(mes)
return
当您键入时,break机器人会写stoped,但不会停止do something在每条消息上说话。
我正在尝试制作一个可以玩井字游戏的机器人。无法从中获取消息内容mes。例如:
@bot.event
async def on_message(mes):
print(int(mes)) # Вызывает ошибку
await bot.process_commands(mes)
完整游戏代码:
@bot.command()
async def play(ctx):
board = Board()
bot_turn = 'O'
game_bot = Bot(True, 'O')
await ctx.send(board)
await ctx.send('[X]: Enter cell number')
@bot.event
async def on_message(mes):
print(mes)
edited = board.edit(mes, 'X') # Здесь (на месте mes) должно быть содержимое сообщения игрока
await ctx.send(board)
if edited:
while True:
cell = game_bot.get_cell(board.get_board(), board.get_void())
bot_edited = board.edit(cell, bot_turn)
if bot_edited:
break
winner = board.is_win()
if winner != False:
if winner == 'O':
statistic['bot win'] += 1
elif winner == 'X':
statistic['player win'] += 1
statistic['total games'] += 1
save_stats(statistic)
await ctx.send(f'[^^]: winner is {winner}')
await bot.process_commands(mes)
if board.is_fill():
statistic['draw'] += 1
statistic['total games'] += 1
save_stats(statistic)
await ctx.send('[^^]: Draw')
await bot.process_commands(mes)
如何input()使用hex颜色代码?
我通常是这样做white = 0xffffff的,但是我在字符串转换时遇到了问题
我需要完全转换为hex,而不是写入字符串ffffff以进一步转换为rgb
编码:
class Color:
def __init__(self, name, val):
self.name = name
self.value = hex(val)
def __str__(self):
return "\n{} - #{}\n".format(self.name, str(self.value).replace('0x', ''))
colors = []
for i in range(1):
n = input('Name: ')
v = input('Value: ')
colors.append(Color(n, v))
输入示例:
Name: White
Value: ffffff
结论:
White - #ffffff
为什么最后一行给出错误以及如何修复它?
import requests
import json
url = 'https://api.color.pizza/v1/212121'
response = requests.get(url)
json_data = json.loads(response.text)['colors']
print('API Response:\n', json.dumps(json_data, indent=4))
name = json_data['name']
结论:
[
{
"name": "Lead",
"hex": "#212121",
"rgb": {
"r": 33,
"g": 33,
"b": 33
},
"hsl": {
"h": 0,
"s": 0,
"l": 12.941176470588237
},
"luminance": 22.062320231562225,
"requestedHex": "#212121",
"distance": 0
}
]
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 9, in <module>
TypeError: list indices must be integers or slices, not str
[Program finished]
我有一个不和谐的机器人,它需要每隔一段时间向聊天室发送一条消息,它做得很好,但现在我无法阻止它。我该怎么做?
编码:
@bot.command()
async def task(ctx, arg):
t = False
i = 0
if arg == 'on':
t = True
elif arg == 'off':
t = False
else:
await ctx.send('Error!')
while t == True:
i += 1
await ctx.send(i)
await asyncio.sleep(10)
我尝试bot.loop.create_task(task(ctx, arg))按照其中一个示例所示进行创建,但我的函数需要ctx并且arg仅在命令内部。
我正在构建一个不和谐的机器人,它会根据要求从 EpicGame 商店提供当前免费的游戏。我以示例中的代码为基础,并将其重新制作为机器人的输出。在页脚中,我想放置一个指向该页面的链接以获取游戏。为此,我需要从 api.get_free_games() 获取“productSluge”或以其他方式获取链接。
它不像那样工作
api.get_free_games()['productSluge']
我正在使用epicstore_api
我需要括号中的部分
https://www.epicgames.com/store/en/product/ <这部分>/home
或完整链接
完整的不和谐机器人命令:
@bot.command()
async def free(ctx):
"""Fetches current free games from the store."""
api = EpicGamesStoreAPI()
free_games = api.get_free_games()['data']['Catalog']['searchStore']['elements']
for game in free_games:
game_name = game['title']
game_thumbnail = None
# Can be useful when you need to also show the thumbnail of the game.
# Like in Discord's embeds for example, or anything else.
# Here I showed it just as example and won't use it.
for image in game['keyImages']:
if image['type'] == 'Thumbnail':
game_thumbnail = image['url']
# print(game_thumbnail)
game_price = game['price']['totalPrice']['fmtPrice']['originalPrice']
game_promotions = game['promotions']['promotionalOffers']
upcoming_promotions = game['promotions']['upcomingPromotionalOffers']
if not game_promotions and upcoming_promotions:
# Promotion is not active yet, but will be active soon.
promotion_data = upcoming_promotions[0]['promotionalOffers'][0]
start_date_iso, end_date_iso = (
promotion_data['startDate'][:-1], promotion_data['endDate'][:-1]
)
# Remove the last "Z" character so Python's datetime can parse it.
start_date = datetime.fromisoformat(start_date_iso)
end_date = datetime.fromisoformat(end_date_iso)
will = ('Игра будет бесплатна с {} по {} UTC.'.format(
start_date, end_date
))
emb = discord.Embed(title=game_name + game_price, description=will, colour=col['AQUA'])
emb.set_footer(text='url')
emb.set_image(url=game_thumbnail)
await ctx.send(embed=emb)
else:
emb = discord.Embed(title='Сейчас БЕСПЛАТНО!', description=game_name + game_price, colour=col['GOLD'])
emb.set_footer(text='url')
emb.set_image(url=game_thumbnail)
await ctx.send(embed=emb)
以 embed.set 开头的所有内容都不起作用
@bot.command()
async def test(ctx):
emb = discord.Embed(
title="Title", description="This is a description", colour=discord.Colour.blue())
# Отсюда не работает
embed.set_footer(text="This is a footer.")
embed.set_image(url="https://cdn.discordapp.com/attachments/520265639680671747/533389224913797122/rtgang.jpeg")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/520265639680671747/533389224913797122/rtgang.jpeg")
embed.set_author(name="Author Name",
icon_url="https://cdn.discordapp.com/attachments/520265639680671747/533389224913797122/rtgang.jpeg")
# До сюда
await ctx.send(embed=emb)
命令前的代码:
import discord
from discord.ext import commands
TOKEN = ''
client = discord.Client()
bot = commands.Bot(command_prefix='$')
错误文字:
Ignoring exception in command test:
Traceback (most recent call last):
File "D:\pyprojects\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "D:/pyprojects/Embed bot/DsBotMain.py", line 48, in test
embed.set_footer(text="This is a footer.")
AttributeError: 'Command' object has no attribute 'set_footer'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\pyprojects\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "D:\pyprojects\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "D:\pyprojects\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'set_footer'