As Israel camped in the plains of Moab beyond the Jordan at Jericho, Balak son of Zippor feared them, because they were many. He sent elders of Moab and Midian with the rewards of divination to Balaam son of Beor at Pethor. God came to Balaam and said, You shall not go with them. You shall not curse the people, for they are blessed. This connects to God's promise to Abraham in Genesis 12:3: I will bless those who bless you.
Balak sent more honorable princes, promising very great honor. Balaam said he could not go beyond Yahweh's word for a house full of silver and gold, yet he asked again. God allowed him to go, but only to do the word He spoke. God's anger burned because he went, and the angel of Yahweh stood in the way as an adversary. The donkey saw the angel three times, turning into a field, pressing against a wall, and then lying down in a narrow place. Each time Balaam struck her.
Yahweh opened the mouth of the donkey: What have I done to you, that you have struck me these three times? Then Yahweh opened the eyes of Balaam, and he saw Yahweh's angel with a drawn sword. The angel said the donkey had saved his life. Balaam confessed, I have sinned. When he reached Balak, he said, I will speak the word that God puts in my mouth. Later Scripture warns that Balaam loved the wages of wrongdoing (2 Peter 2:15). Saying the right words is not the same as having a heart devoted to God.