一般来说,我需要分析监控摄像头的视频,并根据同一对象的给定照片找到特定对象并保存帧。我看到了类似于 Habré 的东西,视频中的对象是确定的,但我不知道如何专门针对我的对象训练模型。另外,分析一定要准确,因为视频里人很多,质量也不是最好的,而且视频里需要找的包裹本身也很单调。有人可以帮助编写代码或至少给出如何实现这一点的想法吗?
S_Smerch's questions
一般来说,情况是这样的,我希望机器人进入语音通道(如果有人在那里),并收听对话,将其记录在文件中以供进一步操作。进入语音通道一切都清楚了,但是如何听声音呢?我深入研究了文档并找到了它voice_client.source
,但此代码未成功打印 None:
audio_data = ctx.voice_client.source
while True:
print(audio_data)
据我了解,您需要创建一个单独的音频流作品,但我根本不知道如何做到这一点。谁能帮忙解答一下?
我正在编写的代码应该与俄语单词和应用程序名称相匹配,并按名称启动最合适的一个。这里原则上是没有问题的,有以下代码进行对比:
from fuzzywuzzy import fuzz
from transliterate import translit
russian_word = translit(input(), 'ru', reversed=True)
data = {'name': '', 'percent': 0}
for app in installed_apps:
percentage = fuzz.ratio(app[:-4], russian_word)
if percentage > data['percent']:
data['percent'] = percentage
data['name'] = app[:-4]
print(data['name'], data['percent'])
但获取已安装应用程序的列表和可执行文件的目录时出现问题。很长一段时间我试图从 gpt 聊天中获取信息,但到处都是。有这样的代码选项:使用winapps
、winreg
、shutil
或pywin32
简单地使用os
。但我没有尝试的一切,一切都运行不完美,要么程序列表不完整,要么大多数程序找不到该目录,要么它指向所有文件(包括卸载程序)。
也就是说,这个想法是什么?您需要找到用于启动使用任何安装程序(从互联网、蒸汽、史诗游戏、微软商店安装)安装的应用程序的可执行文件,并运行它,只知道它的大概名称。简而言之,获取已安装应用程序的列表以及启动它们的直接路径。
PS操作系统:Windows
我正在尝试在pythonanywhereaiogram3
托管上安装电报机器人。但启动时出现错误:。ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]
完整错误:
Traceback (most recent call last):
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore[return-value] # noqa
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1064, in create_connection
raise exceptions[0]
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1049, in create_connection
sock = await self._connect_sock(
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 960, in _connect_sock
await self.sock_connect(sock, address)
File "/usr/local/lib/python3.10/asyncio/selector_events.py", line 500, in sock_connect
return await fut
File "/usr/local/lib/python3.10/asyncio/selector_events.py", line 505, in _sock_connect
sock.connect(address)
OSError: [Errno 101] Network is unreachable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiogram/client/session/aiohttp.py", line 167, in make_request
async with session.post(
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1167, in __aenter__
self._resp = await self._coro
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/client.py", line 562, in _request
conn = await self._connector.connect(
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 540, in connect
proto = await self._create_connection(req, traces, timeout)
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 901, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1209, in _create_direct_connection
raise last_exc
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1178, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 988, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/SmerchTT/bot/main.py", line 170, in <module>
asyncio.run(main())
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/home/SmerchTT/bot/main.py", line 166, in main
await bot.delete_webhook(drop_pending_updates=True)
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiogram/client/bot.py", line 1221, in delete_webhook
return await self(call, request_timeout=request_timeout)
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiogram/client/bot.py", line 432, in __call__
return await self.session(self, method, timeout=request_timeout)
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiogram/client/session/base.py", line 257, in __call__
return cast(TelegramType, await middleware(bot, method))
File "/home/SmerchTT/.local/lib/python3.10/site-packages/aiogram/client/session/aiohttp.py", line 174, in make_request
raise TelegramNetworkError(method=method, message=f"{type(e).__name__}: {e}")
aiogram.exceptions.TelegramNetworkError: HTTP Client says - ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f09a18fffa0>
我查看了其他论坛,他们说您需要使用不同的代理服务器,并在以下位置指定Bot()
:
bot = Bot(token='...', proxy='http://proxy.server:3128')
但班级Bot()
没有争论proxy
,很可能是因为aiogram3
Bot.__init__() got an unexpected keyword argument 'proxy'
还用过图书馆aiohttp-socks
。但没有任何结果。
我正在尝试使用斜杠命令制作一个机器人,其中斜杠命令本身必须不断更新。这是一个代码示例:
@bot.slash_command(name='посещаемость', description='Позволяет посмотреть, кто был на занятиях, в какое время, и сколько находился на них')
async def pos(inter: disnake.CommandInteraction, date:str=commands.Param(name='дата', description='Дата посещаемости', choices=[dt for dt in list(load(open('data/dates.json','r')).keys())])):
await inter.response.send_message(date)
[dt for dt in list(load(open('data/dates.json','r')).keys())]
- 这是一个带有数组键的列表,会不断变化,但程序启动时会读取它,并且不再更新斜杠命令。(迪蛇库)
是否可以以某种方式更新正在运行的代码中的斜杠命令,或者将它们设置为自动更新?
我试图创建一个事件,如果有人离开服务器,那么他将从阵列中删除
代码:
@client.event
async def on_member_remove(member):
with open('users.json', 'r') as f:
users = json.load(f)
users.remove(member.id)
with open('users.json', 'w') as f:
json.dump(users, f)
错误:
AttributeError: 'dict' object has no attribute 'remove'
我试图创建一个领导团队( discord.py),我已经有了一个包含用户的排序数组,但我无法使用其中的数据
数组示例:
{"702338551806951466": {"experience": 45, "level": 3, "need_xp": 70}}
代码本身:
@client.command(aliases=['l', 'лидеры'])
async def leaders(ctx):
with open('users.json', 'r') as f:
users = json.load(f)
users = sorted(users.items(), key=lambda x: x[1]['level'], reverse=True)
embed = discord.Embed(title='Лидеры 🏆', colour=discord.Colour.from_rgb(randint(5,255), randint(5,255), randint(5,255)))
for user in users:
level = user['level'] #ошибка тут
embed.add_field(name=user.name, value=f'Уровень: **{level}**')
await ctx.send(embed=embed)
错误:
TypeError: tuple indices must be integers or slices, not str
如何在循环中获取数组的元素?而如何获取数组的名字,也就是人的id呢?
如何在python中对json数组进行排序?
在这种情况下,我正在尝试实现一个领导者命令( discord.py),该命令需要按级别int 元素对“用户” json 数组进行排序。
大批:
{"947336492487942174": {"experience": 6, "level": 1, "need_xp": 10}, "702338551806951466": {"experience": 7, "level": 3, "need_xp": 10}, "853231575332552704": {"experience": 8, "level": 6, "need_xp": 10}}
代码本身:
@client.command(aliases=['l', 'лидеры'])
async def leaders(ctx):
with open('users.json', 'r') as f:
users = json.load(f)
print(users)
users = sorted(users, key=lambda x: int(x['level']))
embed = discord.Embed(title='Лидеры 🏆', colour=discord.Colour.from_rgb(randint(5,255), randint(5,255), randint(5,255)))
for user in users:
level = int(users[f'{user.id}']['level'])
embed.add_field(name=user, value=f'Уровень: **{level}**')
await ctx.send(embed=embed)
错误:
TypeError: string indices must be integers
如何获取响应命令发送的消息,并响应它。
也就是说,例如:
User1 - text
User2 - reply user1: !command
Bot - reply user1: text2
一个机器人中有一个现成的命令,它可以工作。当我尝试为第二个机器人编写它时,它显示错误:
Command raised an exception: TypeError: timeout() got some positional-only arguments passed as keyword arguments: 'until'
这是命令本身:
@bot.command(aliases=['mute', 'мут', 'мьют', 'timemute'])
@commands.has_permissions(kick_members=True)
async def timeout(ctx, member: discord.Member, time=None, *, reason=None):
author = ctx.author
if member != None:
if time != None:
t = humanfriendly.parse_timespan(time)
await member.timeout(until = discord.utils.utcnow() + datetime.timedelta(seconds=t), reason=reason)
if reason != None:
embed = discord.Embed(
title = 'Mute ✅',
description = f'**{member.mention}** успешно замучен на **{time}**\n\n**Причина: `{reason}`**',
colour = discord.Colour.from_rgb(0, 189, 0)
)
await ctx.send(embed=embed) #await ctx.send (f'**{member.mention}** был замучен на **{time}** по причине **"{reason}"**')
else:
embed = discord.Embed(
title = 'Mute ✅',
description = f'**{member.mention}** успешно замучен на **{time}**',
colour = discord.Colour.from_rgb(0, 189, 0)
)
await ctx.send(embed=embed) #await ctx.send (f'**{member.mention}** был замучен на **{time}**')
else:
embed = discord.Embed(
title = 'Mute ❌',
description = f'{author.mention} укажите время наказания',
colour = discord.Colour.from_rgb(171, 0, 0)
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title = 'Mute ❌',
description = f'{author.mention} укажите кого нужно наказать',
colour = discord.Colour.from_rgb(171, 0, 0)
)
await ctx.send(embed=embed)
问题是什么以及如何解决?
这里有这样一个问题:discord 中出现了“Send to think about your behavior”的功能(类似于 mut)。 当然我想把它放在机器人上:
@bot.command()
async def timeout(ctx, member: discord.Member, time, reason):
await member.timeout(until=time, reason=reason)
await ctx.send(f'Участник {member.mention} был замучен.\nПричина: {reason}')
错误:
CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'timeout'
我试图在互联网上找到解决问题的方法,但没有找到。
我想组建一个能够发布和扮演角色的团队。但它给出了这个错误:
CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'guild'
编码:
@bot.command()
async def leave(ctx):
user = ctx.author.id
ctx.channel.purge(limit=1)
role = ds.utils.get(user.guild.roles, name='Ожидание')
role2 = ds.utils.get(user.guild.roles, name='Вне игры')
user.add_roles(role2)
user.remove_roles(role)
config.players = config.players - 1
谁能告诉我错在哪里?
我正在为不和谐游戏制作机器人。我需要如果角色被从用户手中夺走,那么在我的情况下会执行一些代码config.players = config.players - 1
编码:
@bot.event
async def ...(member):
config.players = config.players - 1
channel = ds.utils.get(user.guild.channels, id=950329905512595466)
await channel.send(f'**{member}** вышел **{config.players}/10')
通过什么方法discord.py
可以做到这一点?
我打算做一个命令!addrole @тест @<role>
,但到目前为止它只是这样:!addrole @тест <role>
。
我需要机器人读取@<role>
命令中标记的内容。
编码:
@bot.command()
async def addrole(ctx, member: ds.Member, role):
dob_role = ds.utils.get(ctx.message.guild.roles, name=role)
await member.add_roles(dob_role)
await ctx.send(f'{member.mention} тебе была назначена роль {dob_role.mention}')
我希望机器人在消息中标记@YouTube。我在网上搜索了,没有找到,所以我在这里问:)
如何在 discord.py 中标记角色?
这是我的整个代码:
from webserver import keep_alive
import json
import sqlite3
import re
import os
from discord.ext import commands
import datetime
import random
import asyncio
import config
import pymongo as mg
import discord as ds
import math
bot = commands.Bot(command_prefix='!', intents=ds.Intents.all())
def str_time_to_seconds(str_time, language='ru'):
conv_dict = {
'w': 'weeks',
'week': 'weeks',
'weeks': 'weeks',
'н': 'weeks',
'нед': 'weeks',
'неделя': 'weeks',
'недели': 'weeks',
'недель': 'weeks',
'неделю': 'weeks',
'd': 'days',
'day': 'days',
'days': 'days',
'д': 'days',
'день': 'days',
'дня': 'days',
'дней': 'days',
'h': 'hours',
'h': 'hours',
'hour': 'hours',
'hours': 'hours',
'ч': 'hours',
'час': 'hours',
'часа': 'hours',
'часов': 'hours',
'm': 'minutes',
'min': 'minutes',
'mins': 'minutes',
'minute': 'minutes',
'minutes': 'minutes',
'мин': 'minutes',
'минута': 'minutes',
'минуту': 'minutes',
'минуты': 'minutes',
'минут': 'minutes',
's': 'seconds',
'sec': 'seconds',
'secs': 'seconds',
'second': 'seconds',
'seconds': 'seconds',
'сек': 'seconds',
'секунда': 'seconds',
'секунду': 'seconds',
'секунды': 'seconds',
'секунд': 'seconds'
}
pat = r'[0-9]+[w|week|weeks|н|нед|неделя|недели|недель|неделю|d|day|days|д|день|дня|дней|h|hour|hours|ч|час|часа|часов|min|mins|minute|minutes|мин|минута|минуту|минуты|минут|s|sec|secs|second|seconds|c|сек|секунда|секунду|секунды|секунд]{1}'
def timestr_to_dict(tstr):
return {conv_dict[p[-1]]: int(p[:-1]) for p in re.findall(pat, str_time)}
def timestr_to_seconds(tstr):
return datetime.timedelta(**timestr_to_dict(tstr)).total_seconds()
def plural(n, arg):
days = []
if language == "ru":
if arg == 'weeks':
days = ['неделя', 'недели', 'недель']
elif arg == 'days':
days = ['день', 'дня', 'дней']
elif arg == 'hours':
days = ['час', 'часа', 'часов']
elif arg == 'minutes':
days = ['минута', 'минуты', 'минут']
elif arg == 'seconds':
days = ['секунда', 'секунды', 'секунд']
elif language == "en":
if arg == 'weeks':
days = ['week', 'weeks', 'weeks']
elif arg == 'days':
days = ['day', 'day', 'days']
elif arg == 'hours':
days = ['hour', 'hour', 'hours']
elif arg == 'minutes':
days = ['minute', 'minute', 'minutes']
elif arg == 'seconds':
days = ['second', 'second', 'seconds']
if n % 10 == 1 and n % 100 != 11:
p = 0
elif 2 <= n % 10 <= 4 and (n % 100 < 10 or n % 100 >= 20):
p = 1
else:
p = 2
return str(n) + ' ' + days[p]
counter_in_str = ""
for i in timestr_to_dict(str_time).items():
counter_in_str += f"{plural(i[1], i[0])} "
return int(timestr_to_seconds(str_time)), counter_in_str
@bot.command()
@commands.has_permissions(administrator = True)
async def оффлайн(ctx):
await bot.change_presence(status = ds.Status.invisible)
@bot.command()
@commands.has_permissions(administrator = True)
async def онлайн(ctx):
await bot.change_presence(status = ds.Status.online
@bot.command(aliases = ['бан'])
@commands.has_permissions(administrator = True)
async def ban(ctx, member: ds.Member, time, reason):
await ctx.send(f'{member.mention} **забанен** \n Продолжительность бана: *{time}* \n Причина бана: *{reason}*')
await member.send(f'Тебя забанили на {time} на сервере {ctx.guild.name} по причине {reason}')
await member.ban(reason=reason)
seconds, str_time = str_time_to_seconds(time)
await asyncio.sleep(seconds)
await member.unban()
await ctx.send(f'*У {member.mention} закончился бан*')
link = await ctx.channel.create_invite(max_age=300)
await member.send(f'У тебя закончился бан на сервере "{ctx.guild.name}"! {link}')
@bot.command()
async def рандом(ctx, par):
r=par.split('-')
await ctx.send(random.randint(int(r[0]), int(r[1])))
@bot.command(aliases = ['размут', 'размьют'])
@commands.has_permissions(administrator = True)
async def unmute(ctx, member: ds.Member):
mute_role = ds.utils.get(ctx.message.guild.roles, name = 'Mute')
await member.remove_roles(mute_role)
await ctx.send(f'{member.mention} *больше не замучен.*')
@bot.command(aliases = ['мут', 'мьют'])
@commands.has_permissions(administrator = True)
async def mute(ctx, user: ds.Member, time, reason):
role = ds.utils.get(ctx.message.guild.roles, name = 'Mute')
await ctx.send(f'**{user.mention} замучен** \n Продолжительность мута: *{time}* \n Причина: *{reason}*')
await user.add_roles(role)
await user.move_to(None)
seconds, str_time = str_time_to_seconds(time)
await asyncio.sleep(seconds)
await user.remove_roles(role)
await ctx.send(f'{user.mention} *больше не замучен*')
#команда unban
@bot.command()
async def инфо(ctx):
await ctx.send('Я первый бот от S_Smerch, я пока мало обучен. Но обещаю что буду в будущем содержать в себе много функций!')
@bot.command()
async def пинг(ctx):
await ctx.send('Понг!')
@bot.command()
async def бот(ctx):
await ctx.send('Сам такой!')
@bot.command()
async def помощь(ctx):
await ctx.send('Все команды: \n **`!помощь`** - вы только что прописали эту команду :) \n **`!инфо`** - информация о боте \n **`!пинг`** - понг! \n **`!бот`** - вы обидете бота :( \n **`!рандом [число]-[число]`** - случайное число \n **`!мут @member`** - мутит человека *(команда для админа)* \n **`!бан [@member] [time] [причина]`** - \n \n Остались вопросы? Пиши на `TT | 𝕊_𝕊𝕞𝕖𝕣𝕔𝕙#2902`!')
keep_alive()
bot.run(os.getenv('TOKEN'))
一切都很好,但停止工作async def <команда>
现在它给出了以下错误:
File "main.py", line 127
async def ban(ctx, member: ds.Member, time, reason):
^
SyntaxError: invalid syntax
因此,不仅是禁令团队,还有其他人……
为什么它不起作用?我的ds:TT | S_Smerch#2902
我想通过这样的命令!офлайн
使它具有“离线”状态,但这样机器人可以继续工作。与!онлайн
,相同!неактивен
。
我有这样的代码:
from webserver import keep_alive
import discord
import json
import sqlite3
import re
import os
from discord.ext import commands
import datetime
import random
from pymongo import MongoClient
import asyncio
import levelsys
cogs = [levelsys]
client = commands.Bot(command_prefix = "!", intents=discord.Intents.all());
bot_channel = 702341394014011425
talk_channels = [702341394014011425]
level = ["🥉Bronze🥉", "🥈Iron🥈", "🥇Gold🥇", "💎Diamond💎", "👑Elite👑"]
levelnum = [5, 10, 20, 30, 50]
cluster = MongoClient("mongodb+srv://<ss>:<12345>@cluster0.vraiu.mongodb.net/Cluster0?retryWrites=true&w=majority")
levelling = cluster["discord"]["levelling"]
class levelsys(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("ready!")
@commands.Cog.listener()
async def on_message(self, message):
if message.channel.id in talk_channels:
stats = levelling.find_one({"id" : message.author.id})
if not message.author.bot:
if stats is None:
newuser = {"id" : message.author.id, "xp" : 100}
levelling.insert_one(newuser)
else:
xp = stats["xp"] + 5
levelling.update_one({"id":message.author.id}, {"$set":{"xp":xp}})
lvl = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
if xp == 0:
await message.channel.send(f'У {message.author.mention} повысился уровень до **{lvl}**!')
for i in range(len(level)):
if lvl == levelnum[1]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[1]))
embed = discord.Embed(description=f"{message.author.mention} ты получил роль **{level[1]}**!")
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
@commands.command()
async def ранг(self, ctx):
if ctx.channel.id == bot_channel:
stats = levelling.find_one({"id" : ctx.author.id})
if stats is None:
embed = discord.Embed(description="Вы не отправляли ни одного сообщения!")
await ctx.channel.send(embed=embed)
else:
xp = stats["xp"]
lvl = 0
rank = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
boxes = int((xp/(200*((1/2) * lvl)))*20)
rankings = levelling.find().sort("xp",-1)
for x in rankings:
rank += 1
if stats["id"] == x["id"]:
break
embed = discord.Embed(title="{} статистика уровней".format(ctx.author.name))
embed.add_field(name="Имя", value=ctx.author.mention, inline=True)
embed.add_field(name="XP", value=f"{xp}/{int(200*((1/2)*lvl))}", inline=True)
embed.add_field(name="Ранг", value=f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Progress Bar [lvl]", value=boxes * ":blue_square:" + (20-boxes) * ":white_large_square:", inline=False)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
@commands.command()
async def лидеры(self, ctx):
if (ctx.channel.id == bot_channel):
rankings = levelling.find().sort("xp",-1)
i = 1
embed = discord.Embed(title="Рейтинг участнков:")
for x in rankings:
try:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"{i}: {temp.name}", value=f"Всего опыта: {tempxp}", inline=False)
i += 1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
但是他:
- 不工作
- 长(在我看来)
如何改善和减少?
我写在replit上