def setUp(self): self.bot = Bot() self.bot.connection.close = MagicMock() db.insert = MagicMock() db.delete = MagicMock() db.select = MagicMock(return_value=[905]) senadores.fetch_ids = MagicMock(return_value=[905]) senadores.fetch_detail = MagicMock(return_value='senador') periodos.fetch_periodos = MagicMock(return_value='periodos') proyectos.fetch_resumen = MagicMock() proyectos.fetch_autores = MagicMock(return_value=[[905, 1], [905, 2]]) proyectos.fetch_new_proyectos = MagicMock( return_value=[{ 'fecha': datetime.now().date(), 'boletin': 905, 'estado': 'test' }]) comisiones.fetch_detail = MagicMock() comisiones.fetch_integrantes = MagicMock(return_value=[{ 'cid': 805, 'pid': 2 }]) comisiones.fetch_proyectos_in_comision = MagicMock( return_value=set(['0-0', '1-0'])) comisiones.fetch_new_comisiones = MagicMock( return_value=[{ 'id': 905, 'nombre': 'test', 'tipo': 'test' }])
async def create_webhook( channel_id: int, bot: Bot, attempt: int = 0 ) -> Union[errors.MissingManageWebhooks, discord.Webhook]: if attempt >= 3: raise errors.WebhookFailed("Got stuck in a loop!") channel = bot.get_channel(channel_id) if not isinstance(channel, discord.TextChannel): raise errors.WebhookChannelNotTextChannel() try: channel_webhooks = await channel.webhooks() except discord.Forbidden: return errors.MissingManageWebhooks() existing_webhooks = [] for webhook in channel_webhooks: assert webhook.user is not None if webhook.user.id == bot.user.id: existing_webhooks.append(webhook) if len(existing_webhooks) == 0: try: webhook = await channel.create_webhook( name=bot.user.name, avatar=await bot.user.avatar_url_as().read()) await bot.db.update_channel( channel_id=channel_id, wipe=True, webhook_token=webhook.token, webhook_id=webhook.id, ) except discord.Forbidden: return errors.MissingManageWebhooks() return webhook elif len(existing_webhooks) == 1: webhook = existing_webhooks[0] stored_webhook = await bot.db.get_channel(channel_id) if webhook.token is None: await webhook.delete() return await create_webhook(channel_id, bot, attempt=attempt + 1) elif (stored_webhook is None or stored_webhook.webhook_token != webhook.token or stored_webhook.webhook_id != webhook.id): await bot.db.update_channel( channel_id=channel_id, wipe=True, webhook_token=webhook.token, webhook_id=webhook.id, ) return webhook else: return webhook else: # More than one webhook by this bot in that channel. THIS SHOULD NOT HAPPEN stored_webhook = await bot.db.get_channel(channel_id) for webhook in existing_webhooks: if (stored_webhook is None # Nothing is stored, delete all or stored_webhook.webhook_token != webhook.token or stored_webhook.webhook_id != webhook.id): # if the webhook does not match the stored one, delete it await webhook.delete() return await create_webhook(channel_id, bot, attempt=attempt + 1)
def test_on_event(self): event = VkBotMessageEvent(raw=self.RAW_EVENT) send_mock = Mock() with patch('main.vk_api.VkApi'): with patch('main.VkBotLongPoll'): bot = Bot('', '') bot.api = Mock() bot.api.messages.send = send_mock bot.on_event(event) send_mock.assert_called_once_with( message=self.RAW_EVENT['object']['text'], random_id=ANY, peer_id=self.RAW_EVENT['object']['peer_id'])
def test_bot_start(self): count = 5 obj = [{'a': 1}] events = [obj] * count long_poller_mock = Mock(return_value=events) long_poller_listen_mock = Mock() long_poller_listen_mock.listen = long_poller_mock with patch('main.vk_api.VkApi'): with patch('main.VkBotLongPoll', return_value=long_poller_listen_mock): bot = Bot('', '') bot.on_event = Mock() bot.start() bot.on_event.assert_called() bot.on_event.assert_any_call(obj) assert bot.on_event.call_count == count
def __init__(self, bot: main.Bot): self.bot = bot with codecs.open(f"config.json", "r", "utf-8") as f: config = json.load(f) self.blacklist = config["blacklist"] log_channel_id = config["log_channel"] muted_role_id = config["muted_role"] self.log_channel = discord.utils.get( bot.get_all_channels(), id=log_channel_id) self.muted_role = discord.utils.get( self.log_channel.guild.roles, id=muted_role_id) self.mutes = self.bot.database.get_mutes()
class TestBot(TestCase): def setUp(self): self.bot = Bot() self.bot.connection.close = MagicMock() db.insert = MagicMock() db.delete = MagicMock() db.select = MagicMock(return_value=[905]) senadores.fetch_ids = MagicMock(return_value=[905]) senadores.fetch_detail = MagicMock(return_value='senador') periodos.fetch_periodos = MagicMock(return_value='periodos') proyectos.fetch_resumen = MagicMock() proyectos.fetch_autores = MagicMock(return_value=[[905, 1], [905, 2]]) proyectos.fetch_new_proyectos = MagicMock( return_value=[{ 'fecha': datetime.now().date(), 'boletin': 905, 'estado': 'test' }]) comisiones.fetch_detail = MagicMock() comisiones.fetch_integrantes = MagicMock(return_value=[{ 'cid': 805, 'pid': 2 }]) comisiones.fetch_proyectos_in_comision = MagicMock( return_value=set(['0-0', '1-0'])) comisiones.fetch_new_comisiones = MagicMock( return_value=[{ 'id': 905, 'nombre': 'test', 'tipo': 'test' }]) def test_run(self): self.bot.actualizar_senadores = MagicMock() self.bot.actualizar_proyectos = MagicMock() self.bot.actualizar_comisiones = MagicMock() self.bot.actualizar_proyectos_por_comision = MagicMock() self.bot.actualizar_asistencias = MagicMock() self.bot.commit_actualizacion = MagicMock() self.bot.run() self.bot.connection.close.assert_called_once() self.bot.actualizar_proyectos.assert_called_once() self.bot.actualizar_comisiones.assert_called_once() self.bot.actualizar_senadores.assert_called_once() self.bot.actualizar_proyectos_por_comision.assert_not_called() self.bot.commit_actualizacion.assert_called_once() def test_run_if_added_leyes(self): self.bot.actualizar_senadores = MagicMock() self.bot.actualizar_proyectos = MagicMock() self.bot.actualizar_comisiones = MagicMock() self.bot.actualizar_proyectos_por_comision = MagicMock() self.bot.actualizar_asistencias = MagicMock() self.bot.commit_actualizacion = MagicMock() self.bot.new_leyes = set([0, 1]) self.bot.run() self.bot.connection.close.assert_called_once() self.bot.actualizar_proyectos.assert_called_once() self.bot.actualizar_comisiones.assert_called_once() self.bot.actualizar_senadores.assert_called_once() self.bot.actualizar_proyectos_por_comision.assert_called_once() self.bot.commit_actualizacion.assert_called_once() def test_should_not_scrap_senadores_if_not_needed(self): self.bot.scrap_new_senadores = MagicMock() self.bot.actualizar_senadores() self.bot.scrap_new_senadores.assert_not_called() def test_should_scrap_senadores_if_needed(self): self.bot.scrap_ids_senadores = MagicMock(return_value=[905, 805]) self.bot.scrap_new_senadores = MagicMock(return_value='senadores') self.bot.agregar_periodos = MagicMock() self.bot.actualizar_senadores() self.bot.scrap_new_senadores.assert_called_once() self.bot.scrap_new_senadores.assert_called_with(set([805])) self.bot.agregar_periodos.assert_called_once() db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'Senadors', 'senadores') def test_should_not_scrap_proyectos_if_not_needed(self): self.bot.scrap_new_proyectos = MagicMock() self.bot.actualizar_proyectos() self.bot.scrap_new_proyectos.assert_not_called() def test_should_scrap_proyectos_if_needed(self): sample_proyectos = [ { 'fecha': datetime.now().date(), 'boletin': 905, 'estado': 'test' }, { 'fecha': datetime.now().date(), 'boletin': 805, 'estado': 'test' }, ] proyectos.fetch_new_proyectos = MagicMock( return_value=sample_proyectos) self.bot.scrap_new_proyectos = MagicMock(return_value='proyectos') self.bot.agregar_senadores_autores = MagicMock() self.bot.actualizar_proyectos() self.bot.scrap_new_proyectos.assert_called_once() self.bot.agregar_senadores_autores.assert_called_once() boletin_called = self.bot.scrap_new_proyectos.call_args_list[0][0][0][ 0]['boletin'] self.assertEqual(boletin_called, 805) self.assertGreater(len(self.bot.new_leyes), 0) db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'Proyectos', 'proyectos') def test_should_not_scrap_comisiones_if_not_needed(self): self.bot.scrap_new_comisiones = MagicMock() self.bot.actualizar_comisiones() self.bot.scrap_new_comisiones.assert_not_called() def test_should_scrap_comisiones_if_needed(self): sample_comisiones = [ { 'id': 905, 'nombre': 'test 0' }, { 'id': 805, 'nombre': 'test 1' }, ] comisiones.fetch_new_comisiones = MagicMock( return_value=sample_comisiones) self.bot.scrap_new_comisiones = MagicMock(return_value='comisiones') self.bot.agregar_integrantes = MagicMock() self.bot.actualizar_comisiones() self.bot.scrap_new_comisiones.assert_called_once() self.bot.agregar_integrantes.assert_called_once() id_called = self.bot.scrap_new_comisiones.call_args_list[0][0][0][0][ 'id'] self.assertEqual(id_called, 805) db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'Comitions', 'comisiones') def test_should_scrap_new_proyectos_in_comisiones_base(self): expected_values = [{'cid': 905, 'pid': 0}, {'cid': 905, 'pid': 1}] self.bot.get_pids_from_boletines = MagicMock( return_value=expected_values) self.bot.new_leyes = set(['0-0', '1-0']) self.bot.actualizar_proyectos_por_comision() db.select.assert_called_with(self.bot.connection, ['id'], 'Comitions') db.insert.assert_called_with(self.bot.connection, 'ProjectComitions', expected_values) self.bot.get_pids_from_boletines.assert_called_once() self.bot.get_pids_from_boletines.assert_called_with([ { 'cid': 905, 'boletin': '0-0' }, { 'cid': 905, 'boletin': '1-0' }, ]) def test_should_assign_comition_0_to_non_existant_project(self): self.bot.get_pids_from_boletines = MagicMock() self.bot.new_leyes = set(['0-0', '2-0']) self.bot.actualizar_proyectos_por_comision() self.bot.get_pids_from_boletines.assert_called_once() self.bot.get_pids_from_boletines.assert_called_with([ { 'cid': 905, 'boletin': '0-0' }, { 'cid': 0, 'boletin': '2-0' }, ]) def test_should_scrap_asistencias(self): sample_proyectos = [ { 'lid': 805, 'fecha_inicio': '2019-11-03', 'fecha_fin': '2020-10-03', 'sid': 905, 'asistencias': 21, 'inasistencias_just': 0, 'inasistencias_no_just': 2 }, { 'lid': 805, 'fecha_inicio': '2019-11-03', 'fecha_fin': '2020-10-03', 'sid': 985, 'asistencias': 16, 'inasistencias_just': 4, 'inasistencias_no_just': 3 }, ] asistencias.fetch_new_asistencias = MagicMock( return_value=sample_proyectos) self.bot.actualizar_asistencias() db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'Assistance', sample_proyectos) def test_should_delete_existing_asistencias(self): sample_proyectos = [ { 'lid': 905, 'fecha_inicio': '2019-11-03', 'fecha_fin': '2020-10-03', 'sid': 905, 'asistencias': 21, 'inasistencias_just': 0, 'inasistencias_no_just': 2 }, ] asistencias.fetch_new_asistencias = MagicMock( return_value=sample_proyectos) self.bot.actualizar_asistencias() db.delete.assert_called_once() db.delete.assert_called_with(self.bot.connection, 'Assistance', '(lid=905 AND sid=905)') def test_should_delete_existing_asistencias_multiple(self): sample_proyectos = [ { 'lid': 905, 'fecha_inicio': '2019-11-03', 'fecha_fin': '2020-10-03', 'sid': 905, 'asistencias': 21, 'inasistencias_just': 0, 'inasistencias_no_just': 2 }, { 'lid': 905, 'fecha_inicio': '2019-11-03', 'fecha_fin': '2020-10-03', 'sid': 985, 'asistencias': 16, 'inasistencias_just': 4, 'inasistencias_no_just': 3 }, ] asistencias.fetch_new_asistencias = MagicMock( return_value=sample_proyectos) self.bot.actualizar_asistencias() db.delete.assert_called_once() db.delete.assert_called_with( self.bot.connection, 'Assistance', '(lid=905 AND sid=905) OR (lid=905 AND sid=985)') def test_should_add_autores(self): self.bot.agregar_senadores_autores([805]) proyectos.fetch_autores.assert_called_once() proyectos.fetch_autores.assert_called_with(805) db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'SenadorProyectos', [[905, 1], [905, 2]]) def test_should_add_periodos(self): self.bot.agregar_periodos([905]) periodos.fetch_periodos.assert_called_once() periodos.fetch_periodos.assert_called_with([905]) db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'Periodos', 'periodos') def test_should_add_integrantes(self): self.bot.agregar_integrantes([905]) comisiones.fetch_integrantes.assert_called_once() comisiones.fetch_integrantes.assert_called_with(905) db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'SenatorComitions', [{ 'cid': 805, 'pid': 2 }]) def test_should_commit_actualizacion(self): self.bot.commit_actualizacion() db.insert.assert_called_once() db.insert.assert_called_with(self.bot.connection, 'Updates', ANY) def test_should_scrap_ids_senadores(self): return_value = self.bot.scrap_ids_senadores() senadores.fetch_ids.assert_called_once() self.assertEqual(return_value, [905]) def test_should_scrap_new_senadores(self): return_value = self.bot.scrap_new_senadores([905, 885]) self.assertEqual(senadores.fetch_detail.call_count, 2) self.assertEqual(['senador', 'senador'], return_value) def test_should_mutate_new_proyectos(self): self.bot.scrap_new_proyectos([{'boletin': 905}, {'boletin': 885}]) self.assertEqual(proyectos.fetch_resumen.call_count, 2) def test_should_mutate_new_comisiones(self): self.bot.scrap_new_comisiones([{'id': 905}, {'id': 885}]) self.assertEqual(comisiones.fetch_detail.call_count, 2)
from main import Bot if __name__ == "__main__": bot = Bot() bot.web_run()
def setup(bot: Bot): bot.add_cog(Api(bot))
def main(): DiscordBot = Bot() DiscordBot.start_bot()
def setup(bot: Bot) -> None: bot.add_cog(AdminCog(bot)) print(" Admin cog!")
def setup(bot: Bot) -> None: bot.add_cog(MessagesCog(bot)) print(" Messages cog!")
from main import Bot import time, random, signal b = Bot() signal.signal(signal.SIGINT, b.exit) while True: b.run(b.config["searchterm"], b.config["targetlink"]) waitTime = max( b.config["averageinterval"] + random.randrange( -b.config["intervalrange"], b.config["intervalrange"]), b.config['mininterval']) b.log(f"Waiting for {waitTime} second(s) before running again.", verbosity=1) time.sleep(waitTime)
from main import Bot if __name__ == '__main__': bot = Bot() summary = bot.create_summary( 'https://www.nytimes.com/2017/10/17/us/politics/alexander-murray-deal-obamacare-subsidies.html?hp&action=click&pgtype=Homepage&clickSource=story-heading&module=first-column-region®ion=top-news&WT.nav=top-news' )
def setup(bot: Bot): bot.add_cog(Verification(bot))
def setup(bot: Bot) -> None: bot.add_cog(ComponentChecking(bot)) print(" Listing cog!")
def setup(bot: Bot) -> None: logic_functions = LogicFunctions(bot) bot.add_cog(SetupCog(bot, logic_functions)) bot.add_cog(SetupCogSlash(bot, logic_functions)) print(" Setup cog!")
def setup(bot: Bot): bot.add_cog(Queue(bot))
from main import Bot_core as Bot bot = Bot() print(bot.specific_send_command('#abc', 'greetings'))
def setup(bot: Bot): bot.add_cog(Enforcement(bot))
def setup(bot: Bot): bot.add_cog(Management(bot))
def setup(bot: Bot): bot.add_cog(Analytics(bot))
def setup(bot: Bot) -> None: bot.add_cog(MainCog(bot)) print(" Main cog!")
def setup(bot: Bot) -> None: bot.add_cog(ListingCog(bot)) print(" Listing cog!")
def setup(bot: Bot): bot.add_cog(Admin(bot))
import asyncio from main import Bot loop = asyncio.get_event_loop() bot = Bot() loop.run_until_complete(bot.prepare()) bot.run(bot.config.get('TOKENS', 'bot'))