Начнем с того, что мой бот ни разу не приостанавливался при работе в одном сабреддите. Однако, как только я добавлю еще 1 или 2, меня забанят, как только мой бот ответит кому-то или группе людей.
Код:
import praw
import random
import re
import sys
import io
# Set stdout encoding to UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# list of quotes to choose from
cat_quotes = [
"Human, have you seen my toy mouse? I left it here somewhere.",
"I'll knock this off the table just to keep things interesting.",
"Pet me. No, stop. Okay, pet me again.",
"I’m not saying I’m a god, but I expect to be treated like one.",
"The red dot... it eludes me, but one day it shall be mine.",
"Nap time? Always.",
"Did someone say treats?",
"The sunbeam calls. I must go nap in it.",
"Is it really so hard to open the can on time, human?",
"I hear everything, but I choose to ignore it.",
"The world is my playground, and everything is my toy.",
"What do you mean ‘off the counter’? This is my throne!",
"The bird outside mocks me. One day, I shall prevail.",
"I see you bought a nice bed for me… I’ll just use the box instead.",
"Why do you insist on closing doors? I must inspect every room at all times.",
"I ignore you to keep you humble.",
"Oh, you wanted to sit here? Too bad, it's my spot now.",
"The vacuum cleaner is my sworn enemy.",
"I knock things over because gravity is fascinating.",
"I’m cute, and I know it. Bow down, human.",
"Sleep is for mortals. I demand attention at 3 a.m.",
"I demand belly rubs… but only for three seconds.",
"My purring isn’t for you. It’s just to show off my power.",
"I heard you talking to another cat. Explain yourself.",
"You exist to serve me. Never forget this.",
"Why do you even own doors? They’re an insult to my curiosity.",
"A box appeared. Naturally, I must investigate.",
"You look like you need some fur on your clothes.",
"Stop scrolling and pet me. This is a command.",
]
# user and app info
username = "_"
pssw = "_"
name = "_"
client_id = "_"
client_secret = "_"
# create reddit instance using user keys
reddit_instance = praw.Reddit(
client_id=client_id,
client_secret=client_secret,
password=pssw,
user_agent=name,
username=username
)
# print(reddit_instance.user.me()) # Test to see if user and pssw work (should return username)
# file used to store comment ids of users to avoid replying to them multiple times by accident
comment_id_file = "comment_id.txt"
# load replies
try:
with open(comment_id_file, "r") as file:
replied_ids = set(file.read().splitlines())
except FileNotFoundError:
replied_ids = set()
# save post and comment IDs that have already been replied to
def save_comment_id():
with open(comment_id_file, "w") as file:
for comment_id in replied_ids:
file.write(f"{comment_id}\n")
# grab the top 10 posts and look through the comments
subreddits = reddit_instance.subreddit("Catswithjobs+cat+cats")
for comment in subreddits.stream.comments():
if comment.id not in replied_ids:
if re.search("Cute", comment.body, re.IGNORECASE):
try:
print(f"Comment: {comment.body}") # comment being replied to
bot_reply = random.choice(cat_quotes)
comment.reply(bot_reply)
print(f"Reply: {bot_reply}") # reply to comment
# append comment id to set and save
replied_ids.add(comment.id)
save_comment_id()
except Exception as e:
print(f"Error replying to comment {comment.id}: {e}")
Что я пробовал:
Регулирование API, чтобы он не вызывал более 40 раз за 1 мин.
Помещаю меру time.sleep(60) между ответами, чтобы я мог отправлять только 1 ответ каждую минуту.
Ограничиваю объем комментариев можно получить, поэтому вместоstream.comments я бы сделал что-то вроде комментариев (limit=30) и таймер сна на 30 секунд, чтобы он мог получать и анализировать только 30 комментариев одновременно, прежде чем придется ждать еще 30 секунд, чтобы получить больше.
Что следует иметь в виду:
На данный момент я создал около 5-7 учетных записей, и все они в конечном итоге были заблокированы
Начнем с того, что мой бот ни разу не приостанавливался при работе в одном сабреддите. Однако, как только я добавлю еще 1 или 2, меня забанят, как только мой бот ответит кому-то или группе людей. Код: [code]import praw import random import re import sys import io
# Set stdout encoding to UTF-8 sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# list of quotes to choose from cat_quotes = [ "Human, have you seen my toy mouse? I left it here somewhere.", "I'll knock this off the table just to keep things interesting.", "Pet me. No, stop. Okay, pet me again.", "I’m not saying I’m a god, but I expect to be treated like one.", "The red dot... it eludes me, but one day it shall be mine.", "Nap time? Always.", "Did someone say treats?", "The sunbeam calls. I must go nap in it.", "Is it really so hard to open the can on time, human?", "I hear everything, but I choose to ignore it.", "The world is my playground, and everything is my toy.", "What do you mean ‘off the counter’? This is my throne!", "The bird outside mocks me. One day, I shall prevail.", "I see you bought a nice bed for me… I’ll just use the box instead.", "Why do you insist on closing doors? I must inspect every room at all times.", "I ignore you to keep you humble.", "Oh, you wanted to sit here? Too bad, it's my spot now.", "The vacuum cleaner is my sworn enemy.", "I knock things over because gravity is fascinating.", "I’m cute, and I know it. Bow down, human.", "Sleep is for mortals. I demand attention at 3 a.m.", "I demand belly rubs… but only for three seconds.", "My purring isn’t for you. It’s just to show off my power.", "I heard you talking to another cat. Explain yourself.", "You exist to serve me. Never forget this.", "Why do you even own doors? They’re an insult to my curiosity.", "A box appeared. Naturally, I must investigate.", "You look like you need some fur on your clothes.", "Stop scrolling and pet me. This is a command.", ]
# user and app info username = "_" pssw = "_" name = "_" client_id = "_" client_secret = "_"
# create reddit instance using user keys reddit_instance = praw.Reddit( client_id=client_id, client_secret=client_secret, password=pssw, user_agent=name, username=username )
# print(reddit_instance.user.me()) # Test to see if user and pssw work (should return username)
# file used to store comment ids of users to avoid replying to them multiple times by accident comment_id_file = "comment_id.txt"
# load replies try: with open(comment_id_file, "r") as file: replied_ids = set(file.read().splitlines()) except FileNotFoundError: replied_ids = set()
# save post and comment IDs that have already been replied to def save_comment_id(): with open(comment_id_file, "w") as file: for comment_id in replied_ids: file.write(f"{comment_id}\n")
# grab the top 10 posts and look through the comments subreddits = reddit_instance.subreddit("Catswithjobs+cat+cats")
for comment in subreddits.stream.comments(): if comment.id not in replied_ids: if re.search("Cute", comment.body, re.IGNORECASE): try: print(f"Comment: {comment.body}") # comment being replied to bot_reply = random.choice(cat_quotes) comment.reply(bot_reply) print(f"Reply: {bot_reply}") # reply to comment
# append comment id to set and save replied_ids.add(comment.id) save_comment_id() except Exception as e: print(f"Error replying to comment {comment.id}: {e}")
[/code] Что я пробовал: [list] [*]Регулирование API, чтобы он не вызывал более 40 раз за 1 мин. [*]Помещаю меру time.sleep(60) между ответами, чтобы я мог отправлять только 1 ответ каждую минуту. Ограничиваю объем комментариев можно получить, поэтому вместоstream.comments я бы сделал что-то вроде комментариев (limit=30) и таймер сна на 30 секунд, чтобы он мог получать и анализировать только 30 комментариев одновременно, прежде чем придется ждать еще 30 секунд, чтобы получить больше. [/list] Что следует иметь в виду: На данный момент я создал около 5-7 учетных записей, и все они в конечном итоге были заблокированы
Очень нубский вопрос. Я пытаюсь писать код с помощью второго пилота, и некоторые (многие) вещи в коде требуют исправления. Однако я не могу пройти мимо этой ошибки. Я установил и импортировал praw, я определил переменную в соответствии с форматом...
Очень нубский вопрос. Я пытаюсь писать код с помощью второго пилота, и некоторые (многие) вещи в коде требуют исправления. Однако я не могу пройти мимо этой ошибки. Я установил и импортировал praw, я определил переменную в соответствии с форматом...
Очень нубский вопрос. Я пытаюсь писать код с помощью второго пилота, и некоторые (многие) вещи в коде требуют исправления. Однако я не могу пройти мимо этой ошибки. Я установил и импортировал praw, я определил переменную в соответствии с форматом...
Очень нубский вопрос. Я пытаюсь писать код с помощью второго пилота, и некоторые (многие) вещи в коде требуют исправления. Однако я не могу пройти мимо этой ошибки. Я установил и импортировал praw, я определил переменную в соответствии с форматом...
Я пытаюсь создать простой метод для печати изображения, но всякий раз, когда я вызываю job.printDialog(), он 1: никогда не возвращает значение, а 2: навсегда блокирует использование моего окна остальной частью программы. Я использую Mac IOS